您可以更改默认构造函数,如下所示:
public SectionsPagerAdapter(@NonNull FragmentManager fm, int behavior, Context mContext) {
super(fm, behavior);
this.mContext = mContext;
}
定义的完整适配器类:
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
@StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2};
private final Context mContext;
public SectionsPagerAdapter(@NonNull FragmentManager fm, int behavior, Context mContext) {
super(fm, behavior);
this.mContext = mContext;
}
@NotNull
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a ProductSearchFragment (defined as a static inner class below).
if(position == 0) {
return new ProductSearchFragment();
} else if(position == 1) {
return new GenericSearchFragment();
}
return new ProductSearchFragment();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
你可以像这样打电话:
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, this);
谢谢。