How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1374
心在旅途
心在旅途 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 01:08

    I encountered this problem when I was trying to get a timer to fire when the fragment in the viewpager was on-screen for the user to see.

    The timer always started just before the fragment was seen by the user. This is because the onResume() method in the fragment is called before we can see the fragment.

    My solution was to do a check in the onResume() method. I wanted to call a certain method 'foo()' when fragment 8 was the view pagers current fragment.

    @Override
    public void onResume() {
        super.onResume();
        if(viewPager.getCurrentItem() == 8){
            foo();
            //Your code here. Executed when fragment is seen by user.
        }
    }
    

    Hope this helps. I've seen this problem pop up a lot. This seems to be the simplest solution I've seen. A lot of others are not compatible with lower APIs etc.

提交回复
热议问题