I'm using tab fragments in an activity and the actionbar hosts the tabs.
What I want to do is that whenever a fragment appears (or re-appears) in the view (selected by the user), I start doing something. I cannot use onResume
of the fragment in this case, since all tabs are never really 'paused' when the user selects another tab, so onResume
is not called
I can use the two following events from the hosting activity, but I don't want them since I expect the fragment should know this logic on its own and do that task. Any idea? tks.
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
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.
The onAttach() callback is invoked when the fragment has been added to a FragmentManager and is attached to its host activity.
If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .
In Android, the fragment is the part of Activity which represents a portion of User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size.
Try setUserVisibleHint() in the fragment as described in this answer. When the fragment is in the selected tab, setUserVisibleHint() will be called with true, and when the fragment is not the selected tab, setUserVisibleHint() will be called with false. This works for me using the support library.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser)
Log.d("MyFragment", "Fragment is visible.");
else
Log.d("MyFragment", "Fragment is not visible.");
}
You can override setUserVisibleHint(boolean isVisibleToUser)
or
onHiddenChanged (boolean hidden)
method.
In case of setUserVisibleHint(boolean isVisibleToUser)
,isVisibleToUser=true
when fragment is visible and isVisibleToUser=false
when fragment is hidden.
In case of onHiddenChanged (boolean hidden)
, hidden:True
if the
fragment is now hidden, false if it is not visible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With