Android: Viewpager inside a fragment of Navigation Drawer
Solution 1
This is definitely possible. You just need to use child fragments for the viewpager. Other than that the implementation is straightforward. Create a custom pager adapter, use the standard viewpager api
Extend FragmentPagerAdapter like so:
private class MyPagerAdapter extends FragmentPagerAdapter
{
public MyPagerAdapter (FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return Fragment1;
case 1:
return Fragment2;
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return FRAGMENT_1_NAME;
case 1:
return FRAGMENT_2_NAME;
}
}
You'll need an layout with a viewpager of course, then just make sure to hook it up like this in Fragment A:
myPagerAdapter = new MyPagerAdapter(this.getChildFragmentManager());
myPager = (ViewPager) mRoot.findViewById(R.id.pager);
myPager.setAdapter(myPagerAdapter);
Note that you'll need to use the support library and support fragments unless your minimum SDK is 4.2 or higher, since the child fragments are API 17
Solution 2
This is possible for Android < 4.2.
In your Fragment A onCreateView
method, when you're inflating the root View
, inflate your layout containing the android.support.v4.view.ViewPager
:
View rootView = inflater.inflate(R.layout.your_viewpager_layout, container, false);
your_viewpager_layout.xml
being something similar to the following:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yourapp.YourActivity" />
Then in your FragmentPagerAdapter.getItem(int position)
method, return the Fragment
you want to display in your ViewPager
, as you would do in a "normal" ViewPager.
Related videos on Youtube
AllenC
Updated on June 25, 2022Comments
-
AllenC almost 2 years
I'm currently developing an Android application what I need is to implement a Viewpager or Tabs inside a fragment of Navigation Drawer. I already implemented the Navigation Drawer from this tutorial: Navigation Drawer Tutorial
Now I have my Navigation Drawer consist of 3 fragments. Fragment A, Fragment B, Fragment C
on Fragment A how can I add a Viewpager for this Fragment?