)
ViewPager 概述ViewPager 是 Android 中实现页面滑动切换的经典组件ViewPager 有如下适配器适配器说明PagerAdapter用于将任意类型的视图与 ViewPager 绑定自由度最高FragmentPagerAdapter当页面数量较少且所有 Fragment 都希望常驻内存、不会被销毁时使用FragmentStatePagerAdapter当页面数量很多或者 Fragment 可能动态增删时使用ViewPager2 是 ViewPager 升级版一、PagerAdapter1、Adapterview_pager_item_image.xml?xml version1.0 encodingutf-8?androidx.constraintlayout.widget.ConstraintLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentImageViewandroid:idid/iv_imageandroid:layout_width200dpandroid:layout_height200dpapp:layout_constraintBottom_toBottomOfparentapp:layout_constraintEnd_toEndOfparentapp:layout_constraintStart_toStartOfparentapp:layout_constraintTop_toTopOfparent//androidx.constraintlayout.widget.ConstraintLayoutImagePagerAdapter.ktclassImagePagerAdapter(privatevalcontext:Context,privatevalimages:ListInt):PagerAdapter(){privatevalinflater:LayoutInflaterLayoutInflater.from(context)overridefungetCount():Int{returnimages.size}overridefunisViewFromObject(view:View,object:Any):Boolean{returnviewobject}overridefuninstantiateItem(container:ViewGroup,position:Int):Any{valviewinflater.inflate(R.layout.view_pager_item_image,container,false)valivImageview.findViewByIdImageView(R.id.iv_image)ivImage.setImageResource(images[position])container.addView(view)returnview}overridefundestroyItem(container:ViewGroup,position:Int,object:Any){super.destroyItem(container,position,object)container.removeView(objectasView)}}2、Activityactivity_view_pager_test.xml?xml version1.0 encodingutf-8?androidx.constraintlayout.widget.ConstraintLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:idid/mainandroid:layout_widthmatch_parentandroid:layout_heightmatch_parenttools:context.ViewPagerTestActivityandroidx.viewpager.widget.ViewPagerandroid:idid/vp_contentandroid:layout_widthmatch_parentandroid:layout_height370dpandroid:background#f5f5f5app:layout_constraintBottom_toBottomOfparentapp:layout_constraintEnd_toEndOfparentapp:layout_constraintStart_toStartOfparentapp:layout_constraintTop_toTopOfparent//androidx.constraintlayout.widget.ConstraintLayoutViewPagerTestActivity.ktclassViewPagerTestActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)enableEdgeToEdge()setContentView(R.layout.activity_view_pager_test)ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)){v,insets-valsystemBarsinsets.getInsets(WindowInsetsCompat.Type.systemBars())v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom)insets}valvpContentfindViewByIdViewPager(R.id.vp_content)vpContent.adapterImagePagerAdapter(this,listOf(R.drawable.image1,R.drawable.image2))}}二、FragmentPagerAdapter1、AdapterMyFragmentPagerAdapter.ktclassMyFragmentPagerAdapter(fm:FragmentManager,privatevalfragments:ListFragment,privatevaltitles:ListString):FragmentPagerAdapter(fm){overridefungetCount():Int{returnfragments.size}overridefungetItem(position:Int):Fragment{returnfragments[position]}overridefungetPageTitle(position:Int):CharSequence?{returntitles[position]}}2、Fragmentfragment_home.xml?xml version1.0 encodingutf-8?LinearLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:orientationverticalTextViewandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:text首页页面android:textSize24sp/Buttonandroid:idid/btn_openandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:layout_marginTop20dpandroid:text打开//LinearLayoutHomeFragment.ktpublicclassHomeFragment extends Fragment{OverridepublicViewonCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){returninflater.inflate(R.layout.fragment_home,container,false);}OverridepublicvoidonViewCreated(NonNullView view,NullableBundle savedInstanceState){super.onViewCreated(view,savedInstanceState);Button btnOpenview.findViewById(R.id.btn_open);btnOpen.setOnClickListener(v-{Toast.makeText(getActivity(),test content,Toast.LENGTH_LONG).show();});}}fragment_discover.xml?xml version1.0 encodingutf-8?LinearLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:orientationverticalTextViewandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:text发现页面android:textSize24sp//LinearLayoutDiscoverFragment.ktpublicclassDiscoverFragment extends Fragment{OverridepublicViewonCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){returninflater.inflate(R.layout.fragment_discover,container,false);}}fragment_profile.xml?xml version1.0 encodingutf-8?LinearLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:orientationverticalTextViewandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:text个人页面android:textSize24sp//LinearLayoutProfileFragment.ktpublicclassProfileFragment extends Fragment{OverridepublicViewonCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){returninflater.inflate(R.layout.fragment_profile,container,false);}}3、Activityactivity_view_pager_test.xml?xml version1.0 encodingutf-8?androidx.constraintlayout.widget.ConstraintLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:idid/mainandroid:layout_widthmatch_parentandroid:layout_heightmatch_parenttools:context.ViewPagerTestActivityandroidx.viewpager.widget.ViewPagerandroid:idid/vp_contentandroid:layout_widthmatch_parentandroid:layout_height370dpandroid:background#f5f5f5app:layout_constraintBottom_toBottomOfparentapp:layout_constraintEnd_toEndOfparentapp:layout_constraintStart_toStartOfparentapp:layout_constraintTop_toTopOfparent//androidx.constraintlayout.widget.ConstraintLayoutViewPagerTestActivity.ktclassViewPagerTestActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)enableEdgeToEdge()setContentView(R.layout.activity_view_pager_test)ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)){v,insets-valsystemBarsinsets.getInsets(WindowInsetsCompat.Type.systemBars())v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom)insets}valvpContentfindViewByIdViewPager(R.id.vp_content)vpContent.adapterMyFragmentPagerAdapter(supportFragmentManager,listOf(HomeFragment(),DiscoverFragment(),ProfileFragment()),listOf(Home,Discover,Profile))}}三、FragmentStatePagerAdapter1、AdapterNewsStatePagerAdapter.ktclassNewsStatePagerAdapter(fm:FragmentManager,privatevalcategories:ListString):FragmentStatePagerAdapter(fm){overridefungetCount():Int{returncategories.size}overridefungetItem(position:Int):Fragment{returnNewsFragment.newInstance(categories[position])}overridefungetPageTitle(position:Int):CharSequence?{returncategories[position]}}2、FragmentNewsFragment.ktclass NewsFragment : Fragment() { companion object { fun newInstance(category: String): NewsFragment { return NewsFragment().apply { arguments Bundle().apply { putString(category, category) } } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return TextView(requireContext()).apply { text arguments?.getString(category) ?: 无 textSize 24f gravity Gravity.CENTER } } }3、Activityactivity_view_pager_test.xml?xml version1.0 encodingutf-8?androidx.constraintlayout.widget.ConstraintLayoutxmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:idid/mainandroid:layout_widthmatch_parentandroid:layout_heightmatch_parenttools:context.ViewPagerTestActivityandroidx.viewpager.widget.ViewPagerandroid:idid/vp_contentandroid:layout_widthmatch_parentandroid:layout_height370dpandroid:background#f5f5f5app:layout_constraintBottom_toBottomOfparentapp:layout_constraintEnd_toEndOfparentapp:layout_constraintStart_toStartOfparentapp:layout_constraintTop_toTopOfparent//androidx.constraintlayout.widget.ConstraintLayoutViewPagerTestActivity.ktclassViewPagerTestActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)enableEdgeToEdge()setContentView(R.layout.activity_view_pager_test)ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)){v,insets-valsystemBarsinsets.getInsets(WindowInsetsCompat.Type.systemBars())v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom)insets}valvpContentfindViewByIdViewPager(R.id.vp_content)vpContent.adapterNewsStatePagerAdapter(supportFragmentManager,listOf(推荐,热点,科技,体育,娱乐))}}