Tabs Using Fragments in Android

Introduction

 
My last article was on the use of basic fragments. It showed how and when to use a fragment. You can find the article at http://www.c-sharpcorner.com/UploadFile/2fd686/fragments-in-android/
 
This article shows one of the major uses of fragments.
 
You might have seen many applications with bottom or top tab bars.
 
In Android we previouslly implemented it using TabActivity and ActivityGroup but now that these two have been deprecated from the Android SDK, we will implement the functionality using fragments.
 
So let's start. Create a new project and create the main class as MainTabActivity.java and a layout file activity_main_tab.xml will be created for you.
 
1. Add two .png files to the "res/drawable" folder for the icons of the tabs and name them tab_icon1.png and tab_icon2.png.
 
2. Create a new file tab_style.xml in "res/drawable" for the background of the tabs. You can check out this article : http://www.c-sharpcorner.com/UploadFile/2fd686/android-buttons-background2/ to create an awesome background but for now you can use this code:
 
tab_style.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.    <!-- state selected -->     
  4.    <item android:state_selected="true">  
  5.       <shape android:shape="rectangle">  
  6.          <gradient  
  7.             android:startColor="#555555"  
  8.             android:centerColor="#444444"  
  9.             android:endColor="#333333"  
  10.             android:angle="90"/>  
  11.          <padding android:left="7dp"  
  12.             android:top="7dp"  
  13.             android:right="7dp"  
  14.             android:bottom="7dp" />  
  15.          <stroke  
  16.             android:width="2dip"  
  17.             android:color="#555555" />  
  18.       </shape>  
  19.    </item>  
  20.    <!-- state normal -->  
  21.    <item>  
  22.       <shape android:shape="rectangle">  
  23.          <gradient  
  24.             android:startColor="#222222"  
  25.             android:centerColor="#181818"  
  26.             android:endColor="#111111"  
  27.             android:angle="90"/>  
  28.          <padding android:left="7dp"  
  29.             android:top="7dp"  
  30.             android:right="7dp"  
  31.             android:bottom="7dp" />  
  32.          <stroke  
  33.             android:width="2dip"  
  34.             android:color="#222222" />  
  35.       </shape>  
  36.    </item>  
  37. </selector> 
3. Create "tabs_icon.xml" in "res/layout", this is the view for the tabs. You can use this code:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.    android:id="@+id/tabsLayout" android:layout_width="fill_parent"  
  3.    android:layout_height="fill_parent" android:background="@drawable/tab_style"  
  4.    android:gravity="center" android:orientation="vertical">  
  5.    <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content"  
  6.       android:layout_weight="1"  
  7.       android:id="@+id/tab_icon" />  
  8.    <TextView  
  9.       android:id="@+id/tab_text"  
  10.       android:layout_width="wrap_content"  
  11.       android:layout_height="wrap_content"  
  12.       android:textColor="#ffffff"  
  13.       android:text="asdfads"  
  14.       android:paddingTop="5dp"  
  15.       android:paddingBottom="2dp"  
  16.       android:textSize="14sp"  
  17.       />  
  18. </LinearLayout> 
4. Create fragment1.xml and fragment2.xml in the "res/layout" folder.
 
fragment1.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.    android:layout_width="match_parent"  
  4.    android:layout_height="match_parent"  
  5.    android:background="#AA1111">  
  6.    <TextView  
  7.       android:layout_height="wrap_content"  
  8.       android:layout_width="wrap_content"  
  9.       android:text="This is Tab 1"  
  10.       android:textSize="20sp"  
  11.       android:textColor="#dddddd"  
  12.       android:layout_centerInParent="true"  
  13.       />  
  14. </RelativeLayout> 
fragment2.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.    android:layout_width="match_parent"  
  4.    android:layout_height="match_parent"  
  5.    android:background="#AAAA11">  
  6.    <TextView  
  7.       android:layout_height="wrap_content"  
  8.       android:layout_width="wrap_content"  
  9.       android:text="This is Tab 2"  
  10.       android:textSize="20sp"  
  11.       android:textColor="#333333"  
  12.       android:layout_centerInParent="true"  
  13.       />  
  14. </RelativeLayout> 
5. Open "activity_main_tab.xml" from the "res/layout" folder, the root element is TabHost that contains the FrameLayout for the fragment and TabWidget to hold the tabs and paste this code.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <TabHost  
  3.    xmlns:android="http://schemas.android.com/apk/res/android"  
  4.    android:id="@android:id/tabhost"  
  5.    android:layout_width="fill_parent"  
  6.    android:layout_height="fill_parent">  
  7.    <LinearLayout  
  8.       android:orientation="vertical"  
  9.       android:layout_width="fill_parent"  
  10.       android:layout_height="fill_parent">  
  11.       <FrameLayout  
  12.          android:id="@android:id/tabcontent"  
  13.          android:layout_width="fill_parent"  
  14.          android:layout_height="0dp"  
  15.          android:layout_weight="1"/>  
  16.       <TabWidget  
  17.          android:id="@android:id/tabs"  
  18.          android:orientation="horizontal"  
  19.          android:layout_width="fill_parent"  
  20.          android:layout_height="wrap_content"  
  21.          android:layout_weight="0"/>  
  22.    </LinearLayout>  
  23. </TabHost> 
6. Now create 2 Java files, Fragment1.java and Fragment2.java, they have the minimum code for a Fragment.
 
Fragment1.java
  1. import android.os.Bundle;  
  2. import android.support.v4.app.Fragment;  
  3. import android.view.LayoutInflater;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6. public class Fragment1 extends Fragment   
  7. {  
  8.  @Override  
  9.  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)   
  10.  {  
  11.   View view = inflater.inflate(R.layout.fragment1, container, false);  
  12.   return view;  
  13.  }  
  14. }  
Fragment2.java
  1. import android.os.Bundle;  
  2. import android.support.v4.app.Fragment;  
  3. import android.view.LayoutInflater;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6. public class Fragment2 extends Fragment   
  7. {  
  8.  @Override  
  9.  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)   
  10.  {  
  11.   View view = inflater.inflate(R.layout.fragment2, container, false);  
  12.   return view;  
  13.  }  

7. Open MainTabActivity.java. I have added comments to the code for the explanation. Paste this code and run the app.
  1. import android.os.Bundle;  
  2. import android.support.v4.app.Fragment;  
  3. import android.support.v4.app.FragmentActivity;  
  4. import android.support.v4.app.FragmentManager;  
  5. import android.support.v4.app.FragmentTransaction;  
  6. import android.view.LayoutInflater;  
  7. import android.view.Menu;  
  8. import android.view.View;  
  9. import android.widget.ImageView;  
  10. import android.widget.TabHost;  
  11. import android.widget.TextView;  
  12. public class MainTabActivity extends FragmentActivity   
  13. {  
  14.  static String TAB_A = "First Tab";  
  15.  static String TAB_B = "Second Tab";  
  16.  TabHost mTabHost;  
  17.  Fragment1 fragment1;  
  18.  Fragment2 fragment2;  
  19.  @Override  
  20.  protected void onCreate(Bundle savedInstanceState)   
  21.  {  
  22.   super.onCreate(savedInstanceState);  
  23.   setContentView(R.layout.activity_main_tab);  
  24.   fragment1 = new Fragment1();  
  25.   fragment2 = new Fragment2();  
  26.   mTabHost = (TabHost) findViewById(android.R.id.tabhost);  
  27.   mTabHost.setOnTabChangedListener(listener);  
  28.   mTabHost.setup();  
  29.   initializeTab();  
  30.  }  
  31.  @Override  
  32.  public boolean onCreateOptionsMenu(Menu menu)   
  33.  {  
  34.   getMenuInflater().inflate(R.menu.activity_main_tab, menu);  
  35.   return true;  
  36.  }  
  37.  public void initializeTab()   
  38.  {  
  39.   TabHost.TabSpec spec = mTabHost.newTabSpec(TAB_A);  
  40.   mTabHost.setCurrentTab(-3);  
  41.   spec.setContent(new TabHost.TabContentFactory()   
  42.   {  
  43.    public View createTabContent(String tag) {  
  44.     return findViewById(android.R.id.tabcontent);  
  45.    }  
  46.   });  
  47.   spec.setIndicator(createTabView(TAB_A, R.drawable.tab_icon1));  
  48.   mTabHost.addTab(spec);  
  49.   spec = mTabHost.newTabSpec(TAB_B);  
  50.   spec.setContent(new TabHost.TabContentFactory()   
  51.   {  
  52.    public View createTabContent(String tag) {  
  53.     return findViewById(android.R.id.tabcontent);  
  54.    }  
  55.   });  
  56.   spec.setIndicator(createTabView(TAB_B, R.drawable.tab_icon2));  
  57.   mTabHost.addTab(spec);  
  58.  }  
  59.  TabHost.OnTabChangeListener listener = new TabHost.OnTabChangeListener()   
  60.  {  
  61.   public void onTabChanged(String tabId)   
  62.   {  
  63.    if (tabId.equals(TAB_A))   
  64.    {  
  65.     pushFragments(tabId, fragment1);  
  66.    }   
  67.    else if (tabId.equals(TAB_B))   
  68.    {  
  69.     pushFragments(tabId, fragment2);  
  70.    }  
  71.   }  
  72.  };  
  73.  public void pushFragments(String tag, Fragment fragment)   
  74.  {  
  75.   FragmentManager manager = getSupportFragmentManager();  
  76.   FragmentTransaction ft = manager.beginTransaction();  
  77.   ft.replace(android.R.id.tabcontent, fragment);  
  78.   ft.commit();  
  79.  }  
  80.  private View createTabView(final String text, final int id)   
  81.  {  
  82.   View view = LayoutInflater.from(this).inflate(R.layout.tabs_icon, null);  
  83.   ImageView imageView = (ImageView) view.findViewById(R.id.tab_icon);  
  84.   imageView.setImageDrawable(getResources().getDrawable(id));  
  85.   ((TextView) view.findViewById(R.id.tab_text)).setText(text);  
  86.   return view;  
  87.  }  

This is the result:
 
Article3Img1.png
 
Article3Img2.png
 
Happy Coding.


Similar Articles