Android ViewPager with FragmentPagerAdapter
Building an Android ui with tabs and swiping views can be done using the ViewPager class, with eventually the FragmentPagerAdapter or FragmentStatePagerAdapter class. In this tutorial we’ll create the ui presented by the screenshot below.I will explain briefly the difference between the two adapters and why we’ll opt for the FragmentPagerAdapter.
What are we creating ?
So this is the sample app we’ll create by the end of the tutorial. The swiping views feature is very consumed in android devolpement. By finishing the tutorial you will be able to implement it.
Android FragmentPagerAdapter vs FragmentStatePagerAdapter
As I already mentionned we can use both of these PagerAdapters with the viewPager class to get a sliding views ui with tabs. The ViewPager class is a sort of layout manager which provides the functionality of flipping data in form of pages, left and right. We can use it for swiping fragments, or for example with a custom circleIndicator class to for swiping indicators.
When using the FragmentPagerAdapter we keep the whole fragment in memory. Its view hierarchy may be destroyed but the fragment may still remain in memory after a swipe. Hence it is advised to use this pagerAdapter only when there are low number of static fragments, since all fragments would be kept in the memory and this would increase the memory heap. Which could result a slow running app.
However, using the FragmentStatePagerAdapter accommodates a large number of fragments in ViewPager. As this adapter destroys the fragment when it is not visible to the user and only savedInstanceState of the fragment is kept for further use. This way a low amount of memory is used and a better performance is delivered in case of dynamic fragments. So the FragmentStatePagerAdapter should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.
Now that the difference between both pagerAdapters is cleared, and that we’ll build a simple sample app with only 3 static fragments, I guess you can tell which of them we’ll use for our demo app .
Creating the project
Building a sliding views ui with the FragmentPagerAdapter takes no more then these four simple steps:
1- Add the viewPager
add the ViewPager widget to your activity_main.xml layout as follows:
<android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.PagerTabStrip android:id="@+id/pager_header" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:paddingBottom="4dp" android:paddingTop="4dp" /> </android.support.v4.view.ViewPager>
The PagerTabStrip is added to show an indicator that displays the pages available at the top. You might want to check out the popular ViewPagerIndicator for more d page indicator customizations.
2- Create the FragmentPagerAdapter
create a TabsPagerAdapter.java class that extends the FragmentPagerAdapter class. Define a NUM_ITEMS int to be returned by the getCount() method. In the getItem() method return an instance of your fragment depending on the position of selected.
public class TabsPagerAdapter extends FragmentPagerAdapter { private int NUM_ITEMS = 3; private String[] titles= new String[]{"First Fragment", "Second Fragment","Third Fragment"}; public TabsPagerAdapter(FragmentManager fm) { super(fm); } // Returns total number of pages @Override public int getCount() { return NUM_ITEMS ; } // Returns the fragment to display for that page @Override public Fragment getItem(int position) { switch (position) { case 0: return new FirstFragment(); case 1: return new SecondFragment(); case 2: return new ThirdFragment(); default: return null; } } // Returns the page title for the top indicator @Override public CharSequence getPageTitle(int position) { return titles[position]; } }
3- Define the fragments
Create three fragments, with a textView and a different background color for each one. Here is the first fragment’s implementation:
fragment_first.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#778899"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="1" android:textStyle="bold" android:textSize="40dp" /> </RelativeLayout>
FirstFragment.java:
public class FirstFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_first, container, false); return view; } }
4- Put it all together
To make all this work together get a reference of your viewPager and use its setAdapter() method to associate it with a new instance of the TabPagerAdapter to it:
MainActivity.java:
public class MainActivity extends AppCompatActivity { private ViewPager viewPager; TabsPagerAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager vpPager = (ViewPager) findViewById(R.id.viewpager); myAdapter = new TabsPagerAdapter(getSupportFragmentManager()); vpPager.setAdapter(myAdapter); } }
That’s all coders ! You can download the code for this sample here.
Recent Comments