packagecom.example.toutiao.ui.page.newsChannel;importandroid.content.Context;importandroid.os.Bundle;importandroid.os.Handler;importandroid.view.Gravity;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroidx.annotation.NonNull;importandroidx.annotation.Nullable;importandroidx.fragment.app.Fragment;importandroidx.lifecycle.Observer;importandroidx.lifecycle.ViewModelProvider;/**
* A simple {@link Fragment} subclass.
* Use the {@link NewsChannelFragment#newInstance} factory method to
* create an instance of this fragment.
*/publicclassNewsChannelFragmentextendsFragment{privateStringmCategory;privateintmIndex;publicNewsChannelFragment(){}/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*/publicstaticNewsChannelFragmentnewInstance(Stringcategory,intindex){NewsChannelFragmentfragment=newNewsChannelFragment();Bundlebundle=newBundle();bundle.putString("category",category);bundle.putInt("index",index);fragment.setArguments(bundle);returnfragment;}@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);mPageViewModel=newViewModelProvider(this).get(PageViewModel.class);if(getArguments()!=null){mCategory=getArguments().getString("category");mIndex=getArguments().getInt("index");}mPageViewModel.setCategory(mCategory);mPageViewModel.setIndex(mIndex);}@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){Viewview=inflater.inflate(R.layout.fragment_news_channel,container,false);// ...
returnview;}}
packagecom.example.toutiao.ui.page.newsChannel;importandroidx.lifecycle.MutableLiveData;importandroidx.lifecycle.ViewModel;/**
* A [ViewModel] for NewsChannelFragment
*/publicclassPageViewModelextendsViewModel{privatefinalMutableLiveData<Integer>mIndex=newMutableLiveData<>();privatefinalMutableLiveData<String>mCategory=newMutableLiveData<>();publicMutableLiveData<String>getCategory(){returnmCategory;}publicvoidsetCategory(Stringcategory){mCategory.setValue(category);}publicMutableLiveData<Integer>getIndex(){returnmIndex;}publicvoidsetIndex(intindex){mIndex.setValue(index);}}
ui/page/newsChannel/SectionsPagerAdapter.java
這裡使用的是最新的 API:FragmentStateAdapter。成員變量 mArrayList 是我們的 Fragment 數組,我們渲染多少頻道就有多大。addFragment 方法添加新的 fragment。
packagecom.example.toutiao.ui.page.newsChannel;importandroidx.annotation.NonNull;importandroidx.fragment.app.Fragment;importandroidx.fragment.app.FragmentManager;importandroidx.lifecycle.Lifecycle;importandroidx.viewpager2.adapter.FragmentStateAdapter;importorg.jetbrains.annotations.NotNull;importjava.util.ArrayList;/**
* A [FragmentStateAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/publicclassSectionsPagerAdapterextendsFragmentStateAdapter{privatefinalArrayList<Fragment>mArrayList=newArrayList<>();publicSectionsPagerAdapter(@NonNullFragmentManagerfragmentManager,@NonNullLifecyclelifecycle){super(fragmentManager,lifecycle);}publicvoidaddFragment(Fragmentfragment){mArrayList.add(fragment);}@NonNull@NotNull@OverridepublicFragmentcreateFragment(intposition){// return your fragment that corresponds to this 'position'
returnmArrayList.get(position);}@OverridepublicintgetItemCount(){// Show total pages.
returnmArrayList.size();}}
packagecom.example.toutiao.ui.home;// ...
importandroidx.annotation.StringRes;importandroidx.fragment.app.Fragment;importandroidx.viewpager2.widget.ViewPager2;importcom.example.toutiao.R;importcom.example.toutiao.activity.SearchActivity;importcom.example.toutiao.ui.page.newsChannel.NewsChannelFragment;importcom.example.toutiao.ui.page.newsChannel.SectionsPagerAdapter;importcom.example.toutiao.ui.searchBar.SearchView;importcom.google.android.material.tabs.TabLayout;importcom.google.android.material.tabs.TabLayoutMediator;/**
* A simple {@link Fragment} subclass.
* Use the {@link com.example.toutiao.ui.home.HomeFragment#newInstance} factory method to
* create an instance of this fragment.
*/publicclassHomeFragmentextendsFragment{privateSectionsPagerAdaptermSectionsPagerAdapter;@StringResprivatestaticfinalint[]TAB_TITLES=newint[]{R.string.title__all__,R.string.title_news_tech,// R.string.title_news_image,
R.string.title_news_hot,R.string.title_news_entertainment,R.string.title_news_game,R.string.title_news_sports,R.string.title_news_finance,R.string.title_digital,};privateViewPager2mViewPagerChannel;privateSearchViewmNewsSearchView;privateTabLayoutmTabsChannel;// // TODO: Rename parameter arguments, choose names that match
//
// // TODO: Rename and change types of parameters
publicHomeFragment(){// Required empty public constructor
}/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment AccountFragment.
*/// TODO: Rename and change types and number of parameters
publicstaticHomeFragmentnewInstance(){HomeFragmentfragment=newHomeFragment();Bundleargs=newBundle();returnfragment;}@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);}@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){// setting status bar's color
WindowmWindow=getActivity().getWindow();mWindow.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);mWindow.setStatusBarColor(getResources().getColor(R.color.tabbed_bg));// Inflate the layout for this fragment
Viewview=inflater.inflate(R.layout.fragment_home,container,false);Contextcontext=container.getContext();// setting tabbed
mSectionsPagerAdapter=newSectionsPagerAdapter(getChildFragmentManager(),getLifecycle());mViewPagerChannel=view.findViewById(R.id.view_pager_channel);// add Fragments in your ViewPagerFragmentAdapter class
for(inti=0;i<TAB_TITLES.length;i++){Stringcategory=context.getString(TAB_TITLES[i]);mSectionsPagerAdapter.addFragment(NewsChannelFragment.newInstance(category,i));}// setting switch Orientation
mViewPagerChannel.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);// setting adapter to view pager
mViewPagerChannel.setAdapter(mSectionsPagerAdapter);mTabsChannel=view.findViewById(R.id.tabs_channel);// setting tabbed
newTabLayoutMediator(mTabsChannel,mViewPagerChannel,(tab,position)->tab.setText(context.getString(TAB_TITLES[position]))).attach();returnview;}}