Android ViewPager Show Multiple Fragments depending on Screen Size

こ雲淡風輕ζ 提交于 2019-12-22 14:14:12

问题


How can one display multiple Fragments 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:


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.

Alternative solutions and more information.



来源:https://stackoverflow.com/questions/23583384/android-viewpager-show-multiple-fragments-depending-on-screen-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!