我尝试了以下但没有帮助。如何从FragmentPagerAdapter设置片段的标签或访问标签?
@Override
public Fragment getItem(int position) {
MainActivity activity = (MainActivity)mcontext;
if (position == 0) {
Fragment discoverFragment = new DiscoverFragment();
activity.getSupportFragmentManager().beginTransaction().add(discoverFragment, "discover").commit();
return discoverFragment;
} else if (position == 1){
Fragment myFeedFragment = new MyFeedFragment();
activity.getSupportFragmentManager().beginTransaction().add(myFeedFragment, "myfeed").commit();
return myFeedFragment;
} else {
Fragment filterFragment = new FilterFragment();
activity.getSupportFragmentManager().beginTransaction().add(filterFragment, "filter").commit();
return filterFragment;
}
}
答案 0 :(得分:1)
您似乎正在正确设置标签。无论如何,这种方式应该有效。
设置标记:
MyFeedFragment myFeedFragment= new MyFeedFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, myFeedFragment, "myfeed");
fragmentTransaction.commit();
然后你可以通过搜索标签获得它:
List fragments = getSupportFragmentManager().getFragments();
Fragment discoverFrag = null;
Fragment myFeedFragment = null;
Fragment filterFragment = null;
for (int i = 0; i < fragments.size(); i++) {
if (((Fragment) fragments.get(i)).getTag() == "discover")
discoverFrag = (Fragment) fragments.get(i);
if (((Fragment) fragments.get(i)).getTag() == "myfeed")
myFeedFragment = (Fragment) fragments.get(i);
if (((Fragment) fragments.get(i)).getTag() == "filter")
filterFragment = (Fragment) fragments.get(i);
}
答案 1 :(得分:0)
将此类用作适配器
class SwipeAdapter extends FragmentPagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private String mPagetile[];
public SwipeAdapter(FragmentManager fm, Context context) {
super(fm);
mPagetile = context.getResources().getStringArray(R.array.pageTitle);
mFragmentManager = fm;
mFragmentTags = new HashMap<>();
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new "Your_fragment";
default:
break;
}
return null;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null)
return null;
return mFragmentManager.findFragmentByTag(tag);
}
@Override
public CharSequence getPageTitle(int position) {
return mPagetile[position];
}
@Override
public int getCount() {
return "Number of fragments";
}
}
现在使用SwipeAdapter实例调用getFrament(int&#34;片段的位置&#34;); 希望你明白。