Android 我是否正确使用FragmentPagerAdapter?
Android 我是否正确使用FragmentPagerAdapter?,android,fragment,Android,Fragment,getItem(),我是否每次都创建片段 使用FragmentPagerAdapter制作fragmentActivity的好例子是什么 我很抱歉问了个愚蠢的问题 public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm);
getItem()
,我是否每次都创建片段
使用FragmentPagerAdapter制作fragmentActivity的好例子是什么
我很抱歉问了个愚蠢的问题
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
switch(position)
{
case 0:
Fragment fragment_tab1 = new MainActivity_Fragment_Tab_02(getApplicationContext());
fragment_tab1.setRetainInstance(true);
return fragment_tab1;
case 1:
Fragment fragment_tab2 = new MainActivity_Fragment_Tab_01(getApplicationContext());
fragment_tab2.setRetainInstance(true);
return fragment_tab2;
case 2:
Fragment fragment_tab3 = new MainActivity_Fragment_Tab_03(getApplicationContext());
fragment_tab3.setRetainInstance(true);
return fragment_tab3;
}
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
看起来还可以,是不是没有按预期工作?getItem()将从viewpager调用一次,然后它会将片段保存在内存中,这样就不必再调用一次 我想改变的一件事是搬家:
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
到
最后在switch案例中,使代码更高效
要了解更多信息,这里有一个很好的例子:如果您有一个静态计数,并且您知道它不会改变,例如活动中的选项卡,那么您应该使用
FragmentStatePagerAdapter
而不是FragmentPagerAdapter
FragmentStatePagerAdapter
将在查看片段时将其保留在内存中,必要时可能会销毁视图层次结构
FragmentPagerAdapter
用于动态内容,每次您滑动并获得另一个片段时,片段将被销毁,但状态将被存储。Thx用于回答Zezeq!!NP如果您对答案感到满意,请投票并/或将其标记为接受答案
default: