Arvids Blog

Thoughts on programming and more

[Android 4] ActionBar with Tabs example

Example Application & Code for ActionBar with Tabs Layout optimized for Android 4.0.
I’am slowly optimizing my apps for Android 4.0 and because there aren’t much Example / Resources I thought I publish my own code as example. It is a simple Layout. Code and anything else after break

First of all we need our which contain the Initializing for our ActionBar Layout:

public class StartActivity extends Activity {
public static Context appContext;

 public void onCreate(Bundle savedInstanceState) {

 //ActionBar gets initiated
 ActionBar actionbar = getActionBar();

 //Tell the ActionBar we want to use Tabs.

 //initiating both tabs and set text to it.
 ActionBar.Tab PlayerTab = actionbar.newTab().setText("Fragment A");
 ActionBar.Tab StationsTab = actionbar.newTab().setText("Fragment B");

 //create the two fragments we want to use for display content
 Fragment PlayerFragment = new AFragment();
 Fragment StationsFragment = new BFragment();

 //set the Tab listener. Now we can listen for clicks.
 PlayerTab.setTabListener(new MyTabsListener(PlayerFragment));
 StationsTab.setTabListener(new MyTabsListener(StationsFragment));

 //add the two tabs to the actionbar

I think the comments explain everything. Next step. The TabListener.

class MyTabsListener implements ActionBar.TabListener {
 public Fragment fragment;

 public MyTabsListener(Fragment fragment) {
 	this.fragment = fragment;

 public void onTabReselected(Tab tab, FragmentTransaction ft) {
 	Toast.makeText(StartActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();

 public void onTabSelected(Tab tab, FragmentTransaction ft) {
 	ft.replace(, fragment);

 public void onTabUnselected(Tab tab, FragmentTransaction ft) {

The method names explain it, onTabSelected we replace our current Fragment with the new Fragment.The Container is fragment_container and a simple LinearLayout.
The Fragments look like this:

public class AFragment extends Fragment {

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 // Inflate the layout for this fragment
 return inflater.inflate(R.layout.afragment, container, false);


This Fragment simple inflate the Layout afragment.xml in the container (defined above)
afragment.xml can be anything, in my example its a simple textview.

The main layout should look like this:

android:layout_height="fill_parent" android:layout_gravity="center">
	 android:layout_height="match_parent" >


You can find the full source code on Github.