Check if fragment is currently visible or no

前端 未结 10 819
悲&欢浪女
悲&欢浪女 2020-12-05 03:10

I know there are lots of similar questions in StackOverflow but my question is little different.

I have nested hierarchy of Fragments like in below structure:

<
10条回答
  •  感动是毒
    2020-12-05 03:38

    When I had a similar problem I solved it by using this hacky method 'going under the hood' like

    Inside your FragmentPagerAdapter(s) add this function.

    public Fragment getActiveFragment(ViewPager container, int position) {
            String name = makeFragmentName(container.getId(), position);
            return fm.findFragmentByTag(name);
        }
    
        private static String makeFragmentName(int viewId, int index) {
            return "android:switcher:" + viewId + ":" + index;
        }
    

    It is not the most graceful solution but as long as it works

    CAUTION

    This is a private method internal to ViewPager that could change at any time or for any OS version.

提交回复
热议问题