How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1317
心在旅途
心在旅途 2020-11-22 00:24

Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible.

For example, I have 2 fragments with

26条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 00:57

    May be very late. This is working for me. I slightly updated the code from @Gobar and @kris Solutions. We have to update the code in our PagerAdapter.

    setPrimaryItem is called every time when a tab is visible and returns its position. If the position are same means we are unmoved. If position changed and current position is not our clicked tab set as -1.

    private int mCurrentPosition = -1;
    
    @Override
    public void setPrimaryItem(@NotNull ViewGroup container, int position, @NotNull Object object) {
        // This is what calls setMenuVisibility() on the fragments
        super.setPrimaryItem(container, position, object);
        if (position == mCurrentPosition) {
            return;
        }
        if (object instanceof YourFragment) {
            YourFragment fragment = (YourFragment) object;
            if (fragment.isResumed()) {
                mCurrentPosition = position;
                fragment.doYourWork();//Update your function
            }
        } else {
            mCurrentPosition = -1;
        }
    }
    

提交回复
热议问题