I successfully configured the tabs in the action bar using the following example from Google itself: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.html as grounds. My code looks like this:
public class Main extends SherlockFragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab tab1 = getSupportActionBar().newTab(); tab1.setIcon(R.drawable.ic_tab_example_selected); tab1.setTabListener(new TabListener<Tab1>(this, "A", Tab1.class)); getSupportActionBar().addTab(tab1); ActionBar.Tab tab2 = getSupportActionBar().newTab(); tab2.setIcon(R.drawable.ic_tab_example_selected); tab2.setTabListener(new TabListener<Tab2>(this, "B", Tab2.class)); getSupportActionBar().addTab(tab2); ActionBar.Tab tab3 = getSupportActionBar().newTab(); tab3.setIcon(R.drawable.ic_tab_example_selected); tab3.setTabListener(new TabListener<Tab3>(this, "C", Tab3.class)); getSupportActionBar().addTab(tab3); ActionBar.Tab tab4 = getSupportActionBar().newTab(); tab4.setIcon(R.drawable.ic_tab_example_selected); tab4.setTabListener(new TabListener<Tab4>(this, "D", Tab4.class)); getSupportActionBar().addTab(tab4); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } public class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final SherlockFragmentActivity mActivity; private final String mTag; private final Class<T> mClass; public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } public void onTabSelected(Tab tab, FragmentTransaction ft) {
In doing so, I have several tabs that switch between different fragments on each tab. However, my problem starts when the tab and change fragments from the tab. This is problem:
When I am in Tab 1 , I replace the initial fragment loaded on the tab with a new fragment. Then I go to Tab 2, which shows its initial fragment. However, the view of the fragment that has changed on tab 1 is still displayed behind the fragment of Tab 2 :
This is the code I'm currently using to change the snippet from tab 1 :
// Create new fragment and transaction FragmentTransaction transaction = ctx.getFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(container, fragment, tag); if(addToBackStack) transaction.addToBackStack(tag); // Commit the transaction transaction.commit();
All this is done through the ActionBar Sherlock and in the Google v4 support library.