For my android application, I am using a viewpager. The viewpager currently hosts one fragment. This is okay on mobile phones, but on tablets, another fragment should be added to the viewpager so that the whole screen is filled.
I have searched around but couldn't find anything about hosting multiple fragments in one viewpager. Is this possible?
What I want:
As I understand, you want to have two fragments inside one page in tablet mode - currently display one by one. You can easily do this by overriding the getPageWidth
method into FragmentStatePagerAdapter
(or FragmentPagerAdapter). This method can be overriding here since FragmentStatePagerAdapter extends PagerAdapter and exists into this last.
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
// Overriding the getWidth method
@Override
public float getPageWidth(int position) {
float nbPages;
// Check the device
if(isTablet(getApplicationContext())) {
nbPages = 2; // 2 fragments / pages
} else {
nbPages = 1; // 1 fragment / pages
}
return (1 / nbPages);
}
}
// The isTablet method
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
Then on tablet device, this adapter displays two fragments in one page whereas on phone device, it displays only one fragment in one page. Tested, works nice!
However, when you said: "another fragment should be added to the viewpager" maybe you meant add dynamically another fragment inside one. In this case, you should try the following tips:
layout-large
folder getChildFragmentManager()
method which allows you to use the nested fragments method. I hope I understand carefully your problem and this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With