Tung Mai Le Tung Mai Le - 1 year ago 100
Android Question

What event is triggered when a tab fragment is selected

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

of the fragment in this case, since all tabs are never really 'paused' when the user selects another tab, so
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.

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.

public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {


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.

public void setUserVisibleHint(boolean isVisibleToUser) {

    if (isVisibleToUser)
        Log.d("MyFragment", "Fragment is visible.");
        Log.d("MyFragment", "Fragment is not visible.");