Swipe views let you navigate between sibling screens, such as tabs, with a
horizontal finger gesture, or
swipe
. This navigation pattern is also referred
to as
horizontal paging
. This topic teaches you how to create a tab layout
with swipe views for switching between tabs, along with how to show a title
strip instead of tabs.
Implement swipe views
You can create swipe views using AndroidX's
ViewPager
widget.
To use a
ViewPager
and tabs, you need to add dependencies for
ViewPager
and
Material Components
to your project.
To set up your layout with
ViewPager
, add the
<ViewPager>
element to your
XML layout. For example, if each page in the swipe view uses the
entire layout, then your layout looks like this:
To insert child views that represent each page, you need to hook this layout to
a PagerAdapter. You can
choose between two kinds of built-in adapters:
FragmentPagerAdapter:
use this when navigating between a small, fixed number of sibling screens.
FragmentStatePagerAdapter:
use this when paging across an unknown number of pages.
FragmentStatePagerAdapter optimizes memory usage by destroying fragments as
the user navigates away.
As an example, here is how you might use FragmentStatePagerAdapter to swipe
across a collection of Fragment objects:
Kotlin
classCollectionDemoFragment:Fragment(){// When requested, this adapter returns a DemoObjectFragment// representing an object in the collection.privatelateinitvardemoCollectionPagerAdapter:DemoCollectionPagerAdapterprivatelateinitvarviewPager:ViewPageroverridefunonCreateView(inflater:LayoutInflater,container:ViewGroup?,savedInstanceState:Bundle?):View? {returninflater.inflate(R.layout.collection_demo,container,false)overridefunonViewCreated(view:View,savedInstanceState:Bundle?){demoCollectionPagerAdapter=DemoCollectionPagerAdapter(childFragmentManager)viewPager=view.findViewById(R.id.pager)viewPager.adapter=demoCollectionPagerAdapter// Since this is an object collection, use a FragmentStatePagerAdapter,// NOT a FragmentPagerAdapter.classDemoCollectionPagerAdapter(fm:FragmentManager):FragmentStatePagerAdapter(fm){overridefungetCount():Int=100overridefungetItem(i:Int):Fragment{valfragment=DemoObjectFragment()fragment.arguments=Bundle().apply{// Our object is just an integer :-PputInt(ARG_OBJECT,i+1)returnfragmentoverridefungetPageTitle(position:Int):CharSequence{return"OBJECT ${(position+1)}"privateconstvalARG_OBJECT="object"// Instances of this class are fragments representing a single// object in the collection.classDemoObjectFragment:Fragment(){overridefunonCreateView(inflater:LayoutInflater,container:ViewGroup?,savedInstanceState:Bundle?):View{returninflater.inflate(R.layout.fragment_collection_object,container,false)overridefunonViewCreated(view:View,savedInstanceState:Bundle?){arguments?.takeIf{it.containsKey
(ARG_OBJECT)}?.apply{valtextView:TextView=view.findViewById(android.R.id.text1)textView.text=getInt(ARG_OBJECT).toString()
publicclassCollectionDemoFragmentextendsFragment{// When requested, this adapter returns a DemoObjectFragment// representing an object in the collection.DemoCollectionPagerAdapterdemoCollectionPagerAdapter;ViewPagerviewPager;@Nullable@OverridepublicViewonCreateView(@NonNullLayoutInflaterinflater,@NullableViewGroupcontainer,@NullableBundlesavedInstanceState){returninflater.inflate(R.layout.collection_demo,container,false);@OverridepublicvoidonViewCreated(@NonNullViewview,@NullableBundlesavedInstanceState){demoCollectionPagerAdapter=newDemoCollectionPagerAdapter(getChildFragmentManager());viewPager=view.findViewById(R.id.pager);viewPager.setAdapter(demoCollectionPagerAdapter);// Since this is an object collection, use a FragmentStatePagerAdapter,// NOT a FragmentPagerAdapter.publicclassDemoCollectionPagerAdapterextendsFragmentStatePagerAdapter{publicDemoCollectionPagerAdapter(FragmentManagerfm){super(fm);@OverridepublicFragmentgetItem(inti){Fragmentfragment=newDemoObjectFragment();Bundleargs=newBundle();// Our object is just an integer :-Pargs.putInt(DemoObjectFragment.ARG_OBJECT,i+1);fragment.setArguments(args);returnfragment;@OverridepublicintgetCount(){return100;@OverridepublicCharSequencegetPageTitle(intposition){return"OBJECT "+(position+1);// Instances of this class are fragments representing a single// object in the collection.publicclassDemoObjectFragmentextendsFragment{publicstaticfinalStringARG_OBJECT="object";@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){returninflater.inflate(R.layout.fragment_collection_object,container,false);@OverridepublicvoidonViewCreated(@NonNullViewview,@NullableBundlesavedInstanceState){Bundleargs=getArguments();((TextView)view.findViewById(android.R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
The following sections show how you can add tabs to help facilitate navigation
between pages.
Add tabs using a TabLayout
A TabLayout provides
a way to display tabs horizontally. When used together with a ViewPager, a
TabLayout provides a familiar interface for navigating between pages in a
swipe view.
Figure 1. A TabLayout with four tabs.
To include a TabLayout in a ViewPager, add a <TabLayout> element inside
the <ViewPager> element, as shown below:
Next, use
setupWithViewPager()
to link the TabLayout to the ViewPager. The individual tabs in the
TabLayout are automatically populated with the page titles from the
PagerAdapter:
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2024-01-03 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-01-03 UTC."],[],[]]