Problem: Fragment onResume()
in ViewPager
is fired before the fragment becomes actually visible.
For example, I have 2 fragments with
setUserVisibleHint(boolean visible) is now deprecated So this is the correct solution
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
In ViewPager2 and ViewPager from version androidx.fragment:fragment:1.1.0
you can just use onPause()
and onResume()
to determine which fragment is currently visible for the user. onResume()
is called when the fragment became visible and onPause
when it stops to be visible.
To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
parameter as the second argument of the FragmentPagerAdapter
constructor.
Add following Code inside fragment
@Override
public void setMenuVisibility(final boolean visible)
{
super.setMenuVisibility(visible);
if (visible && isResumed())
{
}
}
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
}
In ViewPager2
and ViewPager
from version androidx.fragment:fragment:1.1.0
you can just use onPause
and onResume
callbacks to determine which fragment is currently visible for the user. onResume
callback is called when fragment became visible and onPause
when it stops to be visible.
In case of ViewPager2 it is default behavior but the same behavior can be enabled for old good ViewPager
easily.
To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
parameter as second argument of FragmentPagerAdapter
constructor.
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
Note: setUserVisibleHint()
method and FragmentPagerAdapter
constructor with one parameter are now deprecated in the new version of Fragment from android jetpack.
I figured out that onCreateOptionsMenu
and onPrepareOptionsMenu
methods called only in the case of the fragment really visible. I could not found any method which behaves like these, also I tried OnPageChangeListener
but it did not work for the situations, for example, I need a variable initialized in onCreate
method.
So these two methods can be used for this problem as a workaround, specifically for little and short jobs.
I think, this is the better solution but not the best. I will use this but wait for better solution at the same time.
Regards.
I used this and it worked !
mContext.getWindow().getDecorView().isShown() //boolean