get fragment by tag or id from tablayout ,android

后端 未结 1 1197
夕颜
夕颜 2021-02-05 20:46

i use this tutorial for creating tab. and now i have a recyclerview in each fragment and i want to notify them from mainactivity. how to access the adapter in fragment?

1条回答
  •  一向
    一向 (楼主)
    2021-02-05 21:19

    EDIT: After many test, the previous answer work with Android < 21, but for Android > 21 it's little bit weird, it doesn't seems to work in the same way.

    Finally, I solved it like that, and it works everywhere:

    In your adapter:

        HashMap mPageReferenceMap = new HashMap<>();
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        mPageReferenceMap.put(position, fragment);
        return fragment;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
        mPageReferenceMap.remove(position);
    }
    public Fragment getFragment(int key) {
        return mPageReferenceMap.get(key);
    }
    

    And you call getFragment where you want in your activity like that:

    int index = viewPager.getCurrentItem();
    ViewPagerAdapter adapter = ((ViewPagerAdapter)viewPager.getAdapter());
    final YourFragment tabFragment = (YourFragment) adapter.getFragment(index);
    

    PREVIOUS ANSWER :

    Warning : it doesn't really work with Android > 21


    I had the same problem. Finally, i did'nt use id or tag.

    Instead of using:

    CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_custo_tag));
    

    use this:

    CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().getFragments().get(0);
    

    to get instance of CustomFragment.

    I have put get(0) as your position of CustomFragment instance is at zero.

    I found this issue here: Set and get using tag a fragment in android

    0 讨论(0)
提交回复
热议问题