问题
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 constructornewInstance()
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.
来源:https://stackoverflow.com/questions/15744333/viewpager-pages-with-different-layouts-but-same-fragment-class