How to determine when Fragment becomes visible in ViewPager

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

    This seems to restore the normal onResume() behavior that you would expect. It plays well with pressing the home key to leave the app and then re-entering the app. onResume() is not called twice in a row.

    @Override
    public void setUserVisibleHint(boolean visible)
    {
        super.setUserVisibleHint(visible);
        if (visible && isResumed())
        {
            //Only manually call onResume if fragment is already visible
            //Otherwise allow natural fragment lifecycle to call onResume
            onResume();
        }
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        if (!getUserVisibleHint())
        {
            return;
        }
    
        //INSERT CUSTOM CODE HERE
    }
    

提交回复
热议问题