Tablayout With Viewpager Not Working Inside Fragment Android
Hi I have a TabLayout and ViewPager inside a fragment. But I can not slide beetween tab to come to child fragment (Working normally when in Activity but not work in fragment). Here
Solution 1:
I have done a similar project and here is my code for the fragment :
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragmentViewview= inflater.inflate(R.layout.outer_fragment, container, false);
setHasOptionsMenu(true);
ViewPagerviewPager= (ViewPager) view.findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
Log.v("Layout","Tabs");
TabLayouttabLayout= (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setTabTextColors(Color.parseColor("#707070"), Color.parseColor("#FFFFFF"));
assert viewPager != null;
tabLayout.setupWithViewPager(viewPager);
return view;
}
privatevoidsetupViewPager(ViewPager viewPager) {
Adapteradapter=newAdapter(getChildFragmentManager());
adapter.addFragment(newTab1Fragment(), "PHOTOS");
adapter.addFragment(newTab2Fragment(), "HI-FIVES");
viewPager.setAdapter(adapter);
}
staticclassAdapterextendsFragmentPagerAdapter {
privatefinal List<Fragment> mFragments = newArrayList<>();
privatefinal List<String> mFragmentTitles = newArrayList<>();
publicAdapter(FragmentManager fm) {
super(fm);
}
publicvoidaddFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
@Overridepublic Fragment getItem(int position) {
return mFragments.get(position);
}
@OverridepublicintgetCount() {
return mFragments.size();
}
@Overridepublic CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
Solution 2:
You need to use getChildFragmentManager()
in Fragment instead of getFragmentManager()
.
From getChildFragmentManager() documentation
Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
From getFragmentManager() documentation
Return the FragmentManager for interacting with fragments associated with this fragment's activity.
In simple words,
- Use
getChildFragmentManager()
for Child Fragments - Use
getFragmentManager()
for Fragments inside Activity
One can see @this answer for complete code.
Post a Comment for "Tablayout With Viewpager Not Working Inside Fragment Android"