How to determine when Fragment becomes visible in ViewPager

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

    UPDATE: Android Support Library (rev 11) finally fixed the user visible hint issue, now if you use support library for fragments, then you can safely use getUserVisibleHint() or override setUserVisibleHint() to capture the changes as described by gorn's answer.

    UPDATE 1 Here is one small problem with getUserVisibleHint(). This value is by default true.

    // Hint provided by the app that this fragment is currently visible to the user.
    boolean mUserVisibleHint = true;
    

    So there might be a problem when you try to use it before setUserVisibleHint() was invoked. As a workaround you might set value in onCreate method like this.

    public void onCreate(@Nullable Bundle savedInstanceState) {
        setUserVisibleHint(false);
    

    The outdated answer:

    In most use cases, ViewPager only show one page at a time, but the pre-cached fragments are also put to "visible" state (actually invisible) if you are using FragmentStatePagerAdapter in Android Support Library pre-r11.

    I override :

    public class MyFragment extends Fragment {
        @Override
        public void setMenuVisibility(final boolean visible) {
            super.setMenuVisibility(visible);
            if (visible) {
                // ...
            }
        }
       // ...
    }
    

    To capture the focus state of fragment, which I think is the most suitable state of the "visibility" you mean, since only one fragment in ViewPager can actually place its menu items together with parent activity's items.

提交回复
热议问题