First create an action to which you want to attach fragments. In the XML file for this action, add a linear layout, for example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".WoodenSideProject" > <LinearLayout android:id="@+id/fragment_placeholder" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout>
Do not add anything to the XML file. Even a tab node preloaded with Eclipse.
Then create your fragments. First create the user interface for the fragment as you want using the fragment XML file. I will show how to create a fragment with a list:
public class Fragment1Name extends Fragment { public static String TAG="DirectionsFragment"; private String[] list_items = {"Put the list of Strings you want here"}; ListView lView1; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_XML_title, container, false); createListView(view);
Some people suggest extending ListFragment to a fragment that uses a list view. My experience is that this is more of a problem than worth it.
Configure the java Activity file as follows:
public class ActivityName extends FragmentActivity { public static Context appContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_project); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); setTitle("WoodenSideProject"); ActionBar.Tab tab1 = actionBar.newTab().setText("Tab1"); ActionBar.Tab tab2 = actionBar.newTab().setText("Tab2"); ActionBar.Tab tab3 = actionBar.newTab().setText("Tab3"); Fragment Fragment1Name = new Fragment1Name(); Fragment Fragment2Name = new Fragment2Name(); Fragment Fragment3Name = new Fragment3Name(); tab1.setTabListener(new MyTabsListener(Fragment1Name)); tab2.setTabListener(new MyTabsListener(Fragment2Name)); tab3.setTabListener(new MyTabsListener(Fragment3Name)); actionBar.addTab(tab1); actionBar.addTab(tab2); actionBar.addTab(tab3); }
Within the same action, create the following class:
class MyTabsListener implements ActionBar.TabListener { public Fragment fragment; public MyTabsListener(Fragment fragment) { this.fragment = fragment; } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {
I donβt know if others had such problems as I implement tabs of the action bar with fragments, but if they are, I hope this helps. Any suggestions for better implementations would be highly appreciated.