Friday, February 22, 2013

c. How to create Tabs using Action Bar

To create Tabs in Android Tab-host was used earlier. But since it is deprecated and cannot be used anymore, Tabs using Action bar is a better choice. Google is pushing Android Developers to use Action bar instead of hardware menu since it is visible to the user and easily accessible. Action bar can used to host Tabs,Drop Down Lists, Menu settings and even a share button. The only dis advantage of Action Bar is it require API level 13 (ie. 3.2 , Honey Comb )

(TIP) Source code given at the bottom

So today we will learn how to host a tabs using Action Bar.For this we have to create a main Java (Class) file two fragments for two tabs, one main XMl file and two XMl files for two tabs.

 First create a project named "Action Bar Tab Sample " as shown below,
Change the package name to "com.arise.actionbartabsample" instead of "arise" you may use your own name without space. Select minimum SDK required to API level 13.


Click next in the next screen.
Next you can choose a n Icon for your project. You may click beowse and select any image as icon, Eclipse will convert it to icon


Nothing is to be changed in the next screen click next and finish to create your project.


Now create two fragments and two XML file for tabs, as shown below,
right click on the package file ans click new click class to create a new jave file for 1st Fragment


Give it a name "Fragment1" as shown below,


Similerly create "Frgament2" as shown below,



Now create two XMl file by right clicking on the layour folder and click new Android XML file as shown below,




Name the fist XMl file as "tab1" as shown below,


Similarly create another XML file and give the name "tab2"  as shown below,


Now we have to create two buttons in each Fragment and one common EditText for both buttons in Main XML file named activity_main.xml.

First copy the following code in to the Main XML file named activity_main.XMl in the layout folder
Here we are creating a common EditText so that when the buttons are clicked the text will be displayed in the EditText

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >

  
   <EditText
       android:id="@+id/editText1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:inputType="textMultiLine"          
       android:textIsSelectable="true" >   
    <requestFocus />     
    </EditText>   
   
    </LinearLayout>




Now copy the following code in to the MainActivity.java file in the package ,
package com.arise.actionbartabsample; Now I am using Malayalam language custon font for this application so I have to save the font to assets folder and set Typeface as shown below.

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
         final ActionBar actionBar = getActionBar();       
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);         
          
            //setting tabs in to the Action Bar
            Tab tabA = actionBar.newTab();  //Setting Tab A     
            tabA.setTabListener(new TabListener<Fragment1>(this, "Tag A", Fragment1.class));
            tabA.setIcon(R.drawable.tab1); //Setting an Icon for Tab A
            tabA.setText("A"); //Setting Title for Tab A
            actionBar.addTab(tabA); //Adding tab to the Action Bar
           
            Tab tabB = actionBar.newTab();
            tabB.setIcon(R.drawable.tab2);
            tabB.setText("B"); ;       
            tabB.setTabListener(new TabListener<Fragment2>(this, "Tag B", Fragment2.class));
            actionBar.addTab(tabB);
           
            if (savedInstanceState != null) {
                int savedIndex = savedInstanceState.getInt("SAVED_INDEX");
                getActionBar().setSelectedNavigationItem(savedIndex);
            }
           
        }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putInt("SAVED_INDEX", getActionBar().getSelectedNavigationIndex());
       
    }

    public static class TabListener<T extends Fragment>
        implements ActionBar.TabListener{
       
        private final Activity myActivity;
        private final String myTag;
        private final Class<T> myClass;

        public TabListener(Activity activity, String tag, Class<T> cls) {
            myActivity = activity;
            myTag = tag;
            myClass = cls;
                     
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {

            Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
           
            // Check if the fragment is already initialized
            if (myFragment == null) {
                // If not, instantiate and add it to the activity
                myFragment = Fragment.instantiate(myActivity, myClass.getName());
                ft.add(android.R.id.content, myFragment, myTag);
               
            } else {
                // If it exists, simply attach it in order to show it
                ft.attach(myFragment);
            }
                  
           
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
           
            Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
           
            if (myFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(myFragment);
            }
           
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub
           
        }
       
    }
     public void button_method1(View view) //Setting method for Button 1
     
     {


         //setting Malayalam font for the EditText
         EditText et = (EditText)findViewById(R.id.editText1);
         Typeface typeFace1 = Typeface.createFromAsset(getAssets(),"fonts/AnjaliOldLipi.ttf");
          et.setTypeface(typeFace1);
          et.append("അ,A"); //I have used append instead of SetText for adding the text to the already printed text. Otherwise it will replace the first
     }
 public void button_method2 (View view) //Method for Button2
     
     {

       
//setting Malayalam font for the EditText
          EditText et = (EditText)findViewById(R.id.editText1);
         Typeface typeFace1 = Typeface.createFromAsset(getAssets(),"fonts/AnjaliOldLipi.ttf");
          et.setTypeface(typeFace1);
          et.append("ആ,B");
     }
   
    }


To create the Button1 in Tab1.xml file copy the following code,
We have to give a margin at top so that the EditText and button should not overlap.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="100dp"
    android:gravity="center_horizontal" >  
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"          
        android:onClick="button_method1"       
        />
   

</LinearLayout>





Now copy the following code in to Fragment1

package com.arise.actionbartabsample;

import android.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View myFragmentView = inflater.inflate(R.layout.tab1, container, false);
        //Setting Malayalam font for the Button1
        Typeface typeFace1 = Typeface.createFromAsset(myFragmentView.getContext().getAssets(),"fonts/AnjaliOldLipi.ttf");
        //Please note that "createFromAsset(getAssets()" will not work in Fragamant
        Button button_1 = (Button) myFragmentView.findViewById(R.id.button1);   
        //Please note that (Button)findViewById(R.id.button1) will not work in Fragment
        button_1.setTypeface(typeFace1);
        button_1.setText("അ,A");
       
         return myFragmentView;
         
            } 
           

        }


Now create the second button, named button2 in the Fragment2 by copying the code below,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
   
 <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"          
        android:onClick="button_method2"       
        />
</LinearLayout>



Now copy the following code in to the Fragment2.java file

package com.arise.actionbartabsample;

import android.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View myFragmentView = inflater.inflate(R.layout.tab2, container, false);
        //Creating button text using Malayalam font  for button2
        Typeface typeFace1 = Typeface.createFromAsset(myFragmentView.getContext().getAssets(),"fonts/AnjaliOldLipi.ttf");
        //Please note that "createFromAsset(getAssets()" will not work in Fragment
        Button button_2 = (Button) myFragmentView.findViewById(R.id.button2);   
        //Please note that (Button)findViewById(R.id.button1) will not work in Fragment
        button_2.setTypeface(typeFace1);
        button_2.setText("ആ,B");
       
         return myFragmentView;
         
            } 
           

        }

You have to save the custom language font (If you want Local Language in your application) to the assets folder by creating a new folder named "fonts" folder as shown below,


Now we have to give two icons for each tab, to do that open Android manifest File and click "Applications" tab and click "browse" next to "icons"as shown below

now click on "Create new  icons" as shown below,



Now give the icon a name "tab1" as shown below,


Now choose an icon as shown below,





Similarly create another icon with name"tab2" as shown below,



Now click cancel to the child window named "Resource Chooser" as shown below. Remember Don't give Ok since it will replace your application icon.


Now your project is ready to run,
Click run and choose run as "Android Application" as shown below,


Now you will get the result in both the tabs when the buttons are clicked
The following screen shows the results when the button 1 in the Tab1 is clicked


The following result shows when the button2 in the Tab2 is clicked,


So the project is succesfully completed.
You may Download the source code from Here.

2 comments:

  1. Great article and a mini guide to create tabs using action bar. It is very helpful for the newbie. Thanks.
    hire android app developer

    ReplyDelete
  2. Android ActionBar Tab Example: http://www.viralandroid.com/2015/09/android-actionbar-tabs-example.html

    Free Android Tutorial: http://www.viralandroid.com/2015/11/android-tutorial.html

    ReplyDelete

Please give your valuable comments so as to know whether this blog is useful to you.You can also write helpful Android Development Syntax or Shortcuts or Tips.