Viewpager页面与布局不同,但相同的片段类 [英] Viewpager pages with different layouts but same fragment class
问题描述
,我的工作,告诉用户如何使用我的应用程序的指南。
这是我当前如何添加/设置页面:
...
私有类ScreenSlidePagerAdapter扩展FragmentStatePagerAdapter {
公共ScreenSlidePagerAdapter(FragmentManager FM){
超(FM);
} @覆盖
公共片段的getItem(INT位置){
开关(位置){
情况下0:
返回新Guide_fragment();
情况1:
返回新Guide_fragment_2(); 案例2,3,4等。 默认:
返回null;
}
}
...
可是这样我必须为每个网页的片段类,并且由于页面仅图像和文字,我想,它可能不是必要的。
有没有一种方法,我可以只使用相同的片段类的所有页面,然后就分配一个不同的布局呢?
感谢
有没有一种方法,我可以只使用相同的片段类的所有页面,然后就分配一个不同的布局呢?
块引用>当然。数据传递到片段指示要显示什么,一般是通过工厂模式:
创建静态
的newInstance()
方法,它有可能会通常传递给片段构造数据
的newInstance()
接受这些参数,使他们在捆绑
,并附加捆绑<通过/ code>您片段的新构建的实例
setArguments()
您片段,当它需要这些数据,调用
getArguments()
来检索捆绑
这可以确保您的数据将生存的配置更改。
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
解决方案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 aBundle
, and attaches theBundle
to a newly-constructed instance of your fragment viasetArguments()
Your fragment, when it needs this data, calls
getArguments()
to retrieve theBundle
This ensures that your data will survive configuration changes.
这篇关于Viewpager页面与布局不同,但相同的片段类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!