How can one display multiple Fragment
s in a ViewPager
according to the screen size; if it is a small device, it would display 1 Fragment
in one screen. If it is a tablet in landscape mode, it would display 2 Fragment
in a single screen, next to each other. If it is a tablet in portrait mode, it would display 1 Fragment
?

- 1,661
- 1
- 16
- 41
-
http://commonsware.com/blog/2012/08/20/multiple-view-viewpager-options.html – CommonsWare May 10 '14 at 16:29
1 Answers
Inside your ViewPagerAdapter class, override getPageWidth(). It returns a float (default of 1) with the amount of space each page should take up. Changing this value, for example, to .5f will have two fragments appear in the same window.
@Override public float getPageWidth(int position) {
return(1f/simultaneousPages);
}
In addition, setOffscreenPageLimit() should be increased. Its default is one, which means now that we show two pages, not enough fragments will be loaded into memory in the background. As a general rule, this should be twice the amount of pages on each screen.
In MainActivity.java (or whatever activity uses your ViewPagerAdapter)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
// Load extra pages into memory for smooth transitions
viewPager.setOffscreenPageLimit(2*simultaneousPages);
}
To change the view based on screen size, simply change the simultaneousPages variable as appropriate. More on detecting physical screen sizes.
Note: This method will cause problems with PagerTitleStrip and PagerTabStrip. The "current tab" that appears as selected will show as whatever fragment is the furthest left on your view.