How to use setUserVisibleHint in Fragment on Android

As setUserVisibleHint(boolean aBoolean) is now deprecated, for those who still want to know when a fragment is visible you can still use

 public FragmentTransaction setMaxLifecycle(Fragment fragment, Lifecycle.State state)

either indirectly with a FragmentPagerAdapter (or FragmentStatePagerAdapter) just by using the new Constructor

MyFPagerAdapter(FragmentManager fm) {
        super(fm ,FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
       //...
}

note that FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT allows the adapter to use setMaxLifecycle internally (through setPrimaryItem) instead of setUserVisibleHint. Hence in your fragment's implementation you won't anymore need to use

setUserVisibleHint(boolean aBoolean)

but instead, onResume() cause now onResume() will be called only for the visible fragment. the rest ones will still be able to reach onCreateView().

The direct way is by using setMaxLifeCycle with FragmentTransaction when adding or switching fragment, where then

setMaxLifecycle(fragment, Lifecycle.State.STARTED);

is equivalent

setUserVisibleHint(false);

and

setMaxLifecycle(fragment, Lifecycle.State.RESUMED);

equivalent to

setUserVisibleHint(true);

then again listen with Fragment's onResume() callback


After AndroidX setUserVisibleHint is deprecated as a replacement we can use the setMenuVisibility Method.

  override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
  }

Before you put this code you know about fragment life cycle

 override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
           // post your code
        }
    }

    override fun onStart() {
        super.onStart()
        userVisibleHint = true
    }