Check if fragment is currently visible or no

前端 未结 10 800
悲&欢浪女
悲&欢浪女 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:59

    We can easily map which fragment is now visible using mViewPager.getCurrentItem() method. This method gives int value number from which we can find the current fragment.

    -- For access and get this method result we have two options:

    1. make Static viewPager instance in activity and use wherever we want
    2. again make viewPager instance in fragment (findViewById())

    and using one from above two methods getCurrentItem() in fragment to find which fragment is visible now.

    For example,

    1. In MainActivity (activity which is used for ViewPager) define

    public static ViewPager mViewPager;

    • In Fragment, MainActivity.mViewPager.getCurrentItem() to get current fragment

    Also, method that shows which fragment is visible:

    public void whichIsVisible() {
        String msg = "";
        int curFragNo = MainActivity.mViewPager.getCurrentItem();
        switch (curFragNo) {
            case 0:
                msg = "AFragment is visible.";
                break;
            case 1:
                msg = "BFragment is visible.";
                break;
            case 2:
                msg = "CFragment is visible.";
                break;
            case 3:
                msg = "DFragment is visible.";
                break;
        }
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
    

    (2) For non-static use,

    • get viewPager instance in fragment by below code,

    viewPager=(ViewPager) view.getRootView().findViewById(R.id.container);

    and then

    viewPager.getCurrentItem() to get index and find current visible fragment as per use.

提交回复
热议问题