gpt4 book ai didi

android - 如何在 FragmentPagerAdapter 中添加 fragment 标签以便稍后引用 fragment ?

转载 作者:行者123 更新时间:2023-11-30 00:32:05 31 4
gpt4 key购买 nike

我尝试了以下但没有帮助。如何从 FragmentPagerAdapter 设置标签或访问 fragment 标签?

        @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;
}
}

最佳答案

看来您正确设置了标签。无论如何,这种方式应该可行。

设置标签:

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);
}

关于android - 如何在 FragmentPagerAdapter 中添加 fragment 标签以便稍后引用 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44132964/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com