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
?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments