How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1375
心在旅途
心在旅途 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:50

    Another solution posted here overriding setPrimaryItem in the pageradapter by kris larson almost worked for me. But this method is called multiple times for each setup. Also I got NPE from views, etc. in the fragment as this is not ready the first few times this method is called. With the following changes this worked for me:

    private int mCurrentPosition = -1;
    
    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
    
        if (position == mCurrentPosition) {
            return;
        }
    
        if (object instanceof MyWhizBangFragment) {
            MyWhizBangFragment fragment = (MyWhizBangFragment) object;
    
            if (fragment.isResumed()) {
                mCurrentPosition = position;
                fragment.doTheThingYouNeedToDoOnBecomingVisible();
            }
        }
    }
    

提交回复
热议问题