Created
December 31, 2012 20:41
-
-
Save MadMaxMcKinney/4422595 to your computer and use it in GitHub Desktop.
Android 3.0+ TabListener.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class TabListener<T extends Fragment> implements | |
ActionBar.TabListener { | |
private Fragment mFragment; | |
private final Activity mActivity; | |
private final String mTag; | |
private final Class<T> mClass; | |
// Constructor - set the variables up from when you call the method somewhere else | |
public TabListener(Activity activity, String tag, Class<T> clz) { | |
mActivity = activity; | |
mTag = tag; | |
mClass = clz; | |
} | |
public void onTabSelected(Tab tab, FragmentTransaction ft) { | |
// Check if the fragment is already initialized | |
if (mFragment == null) { | |
// If not, instantiate and add it to the activity | |
mFragment = Fragment.instantiate(mActivity, mClass.getName()); | |
ft.add(android.R.id.content, mFragment, mTag); | |
} else { | |
// If it exists, simply attach it in order to show it | |
ft.attach(mFragment); | |
} | |
} | |
public void onTabUnselected(Tab tab, FragmentTransaction ft) { | |
if (mFragment != null) { | |
// Detach the fragment, because another one is being attached | |
ft.detach(mFragment); | |
} | |
} | |
public void onTabReselected(Tab tab, FragmentTransaction ft) { | |
// User selected the already selected tab. Usually do nothing. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment