Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Host multiple fragments in viewpager

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:

enter image description here

like image 924
Arnout Avatar asked Oct 21 '22 11:10

Arnout


1 Answers

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:

  • Create the layout-large folder
  • Duplicate your Fragment's layout (which is one page in your ViewPager) inside it
  • And with a LinearLayout, you can set the right side to another Fragment OR with a FrameLayout, you can add the new fragment thanks to getChildFragmentManager() method which allows you to use the nested fragments method.

I hope I understand carefully your problem and this will help you.

like image 122
Blo Avatar answered Oct 23 '22 03:10

Blo