How to test if a fragment view is visible to the user?

前端 未结 10 450
闹比i
闹比i 2020-11-28 04:42

I have a ViewPager, each page is a Fragment view. I want to test if a fragment is in a visible region. the Fragment.isVisible only test

  • the fragment is attache
相关标签:
10条回答
  • 2020-11-28 05:15

    This is what I use to determine the visibility of a fragment.

    private static boolean m_iAmVisible;
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) { 
        super.setUserVisibleHint(isVisibleToUser);
        m_iAmVisible = isVisibleToUser;
    
        if (m_iAmVisible) { 
            Log.d(localTAG, "this fragment is now visible");
        } else {  
            Log.d(localTAG, "this fragment is now invisible");
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:18

    setUserVisibleHint probably may not be called, onHiddenChanged may be called not every time when another fragment is being closed. So, you may rely on onResume (and onPause), but it is usually called too often (for example, when you turn on a device screen). Also in some situations it is not called, you should manage current fragment in host activity and write:

    if (currentFragment != null) {
        currentFragment.onResume();
    }
    
    0 讨论(0)
  • 2020-11-28 05:18

    Kotlin:

    if (userVisibleHint) {
        // the fragment is visible
    } else {
        // the fragment is not visible
    }
    

    Java

    if (getUserVisibleHint()) {
        // the fragment is visible
    } else {
        // the fragment is not visible
    }
    

    https://developer.android.com/reference/android/app/Fragment.html#getUserVisibleHint()

    https://stackoverflow.com/a/12523627/2069407

    0 讨论(0)
  • 2020-11-28 05:27

    If you know what "page" each fragment is attached to you could use ViewPager.getCurrentItem() to determine which fragment is "visible".

    0 讨论(0)
提交回复
热议问题