我设法确定如何做到这一点,但我不知道这是最好的方法。我必须做的是将一个布尔值传递到我的 FragmentPagerAdapter 实现中,并且仅在我处于搜索模式时才允许创建一个片段。
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
boolean isSearching = false;
public SectionsPagerAdapter(FragmentManager fm, boolean isSearching) {
super(fm);
this.isSearching = isSearching;
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
Fragment fragment = null;
switch (position) {
case 0:
fragment = new UserGeneralFragment();
break;
case 1:
if (!isSearching) fragment = new CommentListFragment();
break;
}
return fragment;
}
@Override
public int getCount() {
if (!isSearching) return 2;
else return 1;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.activity_user_tab_general).toUpperCase(l);
case 1:
if (!isSearching) return getString(R.string.activity_user_tab_comments).toUpperCase(l);
break;
}
return null;
}
}