实现ActionBar.TabListener接口
public static class TabListener<T extends Fragment> implements ActionBar.TabListener{ private Fragment mFragment; private final Activity mActivity; private final String mTag; private final Class<T> mClass; public TabListener(Activity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { 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 { ft.attach(mFragment); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { ft.detach(mFragment); } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } }
1 protected void onCreate(Bundle savedInstanceState) { 2 super.onCreate(savedInstanceState); 3 4 ActionBar actionBar = getActionBar(); 5 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 6 actionBar.setDisplayShowTitleEnabled(false); 7 8 Tab tab = actionBar.newTab() 9 .setText("tab1") 10 .setTabListener(new TabListener<PlaceholderFragment>( 11 this, "artist", PlaceholderFragment.class)); 12 actionBar.addTab(tab); 13 14 tab = actionBar.newTab() 15 .setText("tab2") 16 .setTabListener(new TabListener<PlaceholderFragment>( 17 this, "album", PlaceholderFragment.class)); 18 actionBar.addTab(tab); 19 20 }