Viewpager pages with different layouts but same fragment class

余生长醉 提交于 2020-01-25 20:04:47

问题


Using a ViewPager, I'm working on a guide that tells the user how to use my app.

This is how i currently add/setup the pages:

    ...
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            return new Guide_fragment();
        case 1:
            return new Guide_fragment_2();

        case 2,3,4 etc.

        default:
            return null;
        }
    }
            ...

But this way I have to have a fragment class for each page, and since the pages are only images and text, I figured that it might not be necessary.

Is there a way I can just use the same fragment class for all pages and then just assign a different layouts to it?

Thanks


回答1:


Is there a way I can just use the same fragment class for all pages and then just assign a different layouts to it?

Sure. Pass data into the fragment indicating what to display, typically via the factory pattern:

  • Create a static newInstance() method that takes the data you might ordinarily pass to the fragment constructor

  • newInstance() takes those parameters, puts them in a Bundle, and attaches the Bundle to a newly-constructed instance of your fragment via setArguments()

  • Your fragment, when it needs this data, calls getArguments() to retrieve the Bundle

This ensures that your data will survive configuration changes.



来源:https://stackoverflow.com/questions/15744333/viewpager-pages-with-different-layouts-but-same-fragment-class

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