ActionBar provide tab navigation which used Fragment System.
Proccess in Activity#onCreate
- Set Navigation Mode to ActionBar.
- Create tab that is used Action#newTab().
- Set TabListener with Fragment to show tab selected.
If you do not want to show Title and Icon, you need to call actionBar.setDisplayShowTitleEnabled(false) and actionBar.setDisplayShowHomeEnabled(false).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// setup action bar for tabs
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// hide Title and Icon
// actionBar.setDisplayShowTitleEnabled(false);
// actionBar.setDisplayShowHomeEnabled(false);
Tab tab = actionBar.newTab();
tab.setText("artist");
tab.setTabListener(new TabListener(this, "artist", ArtistFragment.class) );
actionBar.addTab(tab);
tab = actionBar.newTab();
tab.setText("album");
tab.setTabListener(new TabListener(this, "album", AlbumFragment.class));
actionBar.addTab(tab);
}
Create TabListener with Fragment to show tab selected.
private class TabListenerimplements ActionBar.TabListener { private Fragment mFragment; private final Activity mActivity; private final String mTag; private final Class mClass; /** * Constructor used each time a new tab is created. * * @param activity * The host Activity, used to instantiate the fragment * @param tag * The identifier tag for the fragment * @param clz * The fragment's Class, used to instantiate the fragment */ public TabListener(Activity activity, String tag, Class clz) { mActivity = activity; mTag = tag; mClass = clz; } /* The following are each of the ActionBar.TabListener callbacks */ 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. } }
Called the order
When Application launched,Called the order.onCreate
↓
onTabSelected of "artist"
↓
ArtistFragment#onCreateView
Select Album Tab.
onTabUnselected of "artist"
↓
onTabSelected of "album"
↓
AlbumFragment#onCreateView
Reselect Album Tab.
onTabReselected of "album"

No comments:
Post a Comment