What event is triggered when a tab fragment is selected

EyeQ Tech picture EyeQ Tech · May 31, 2014 · Viewed 14.2k times · Source

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) {
    }

Answer

Doug Simonton picture Doug Simonton · May 31, 2014

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.");
}