Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a ViewPager inside a Fragment

I need to place a ViewPager inside of a fragment, but I have two fragments, Fragment 1 is my MENU, and Fragment 2 I want to use as a ViewPagerIndicator.

But a fragment can't have another fragment... what do I need to do for that?

enter image description here

like image 237
Gilberto Ibarra Avatar asked Sep 29 '13 01:09

Gilberto Ibarra


People also ask

Can you put a ViewPager in a fragment?

Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class.


2 Answers

Starting in Android 4.2, there are nested fragments.http://developer.android.com/about/versions/android-4.2.html#NestedFragments The support library now also includes support for this for older Android versions.

So you can do something like this:

@Override     public void onViewCreated(View view, Bundle savedInstanceState) {     super.onViewCreated(view, savedInstanceState);      ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);     mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));     } 

Full implementation available here: https://github.com/marcoRS/nested-fragments/tree/master/src/com/burnside/digital/nestedfragments

like image 65
Ryan S Avatar answered Sep 22 '22 14:09

Ryan S


You must use getChildFragmentManager() instead of getSupportFragmentManager() to get the FragmentManger inside a Fragment. But you should not use FragmentStatePagerAdapter rather than FragmentPagerAdapter.

like image 20
hawa11 Avatar answered Sep 19 '22 14:09

hawa11