Friday 6 June 2014

Android Swipeable Tab Layout Example | How to create Swipeable Tab Layout Using Fragment in Android.

Swipeable Tab Layout is very frequently used in most of the android apps. It gives a user friendly UI as well instead of going next page users can get several tabs options within one page by swipeable action.  Here in my MusicPlayer example I have taken 3 tabs in main page fragment as Album, Atrists,Songs.



 We need following files and steps to do:

1. A parent fragment where all 3 child fragments will sit. (.xml file).
2.  Three child fragments for three tabs layout (.xml file).
3.  Main activity java file which will extend FragmentActivity. Here we will define the functionality and tabListener events.
4.An FragmentPagerAdapter which will set child fragments into parent.
5. Three separate fragments java file which will define the layout and views in child fragments.

Step-1: Create parent fragment xml file as activity_main.xml. Add the viewPager as following:

    <android.support.v4.view.ViewPager 
    xmlns:android="http://schemas.android.com/apk/res/android"                
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

 Our activity_main.xml. will be like this:

activity_main.xml :

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="#8D8488" >
<!--Add ViewPager -->
     <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>
   
</RelativeLayout>


Step-2: Create 3 child xml file for 3 child fragments. Go to layout folder and create 3 xml files.
In these tabs, design your layouts as you want to see in each tabs. Here I have designed simply in RelativeLayout.
Mine looks like this.

 album.xml : 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#44ADEE">
<!--Add your views in layout what you wanna design -->
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="18dp"
        android:text="Fallining into You"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="14dp"
        android:text="Minutes to Midnight"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="16dp"
        android:text="Dangerous"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="14dp"
        android:text="The Hunting Party"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="27dp"
        android:layout_marginTop="30dp"
        android:text="Thriller"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

artists.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FA79B1" >
<!--Add your views in layout what you wanna design -->
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="26dp"
        android:layout_marginTop="32dp"
        android:text="Michael Jackson"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="14dp"
        android:text="Akon"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="15dp"
        android:text="Rihana"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="14dp"
        android:text="Shakira"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="18dp"
        android:text="Enrique Eglesias"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

songs.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#44EEDD" >
<!--Add your views in layout what you wanna design -->
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="29dp"
        android:text="Love Story"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="16dp"
        android:text="Sombody wants you"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="18dp"
        android:text="Lonely"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="14dp"
        android:text="In the End"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="14dp"
        android:text="That&apos;s my name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Our designing part is over. Now let’s see our coding part.

Step-3: Go to src folder and create class for all three child fragments .
           Extend your ChildFrgment class by Fragment

   AlbumFragment.java

package com.allandroidprojects.musicplayer;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class AlbumFragment extends Fragment {
      
       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
              //Find your views
              View rootView = inflater.inflate(R.layout.album, container, false);
              TextView tvThriller=(TextView) rootView.findViewById(R.id.textView1);
              TextView tvMtoM=(TextView) rootView.findViewById(R.id.textView2);
              return rootView;
       }
 }

Step-4: Create ArtistsFragment.java in src  folder.

ArtistsFragment.java

package com.allandroidprojects.musicplayer;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ArtistsFragment extends Fragment {

      
              public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
                     //Find your views
                     View rootView = inflater.inflate(R.layout.artists, container, false);
                     TextView tvMichael=(TextView) rootView.findViewById(R.id.textView1);
                     TextView tvAkon=(TextView) rootView.findViewById(R.id.textView2);
                     return rootView;
              }    
}

Step-5: Create SongsFragment.java  in src  folder.

SongsFragment.java  

package com.allandroidprojects.musicplayer;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SongsFragment extends Fragment {

       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
              //Find your views
              View rootView = inflater.inflate(R.layout.songs, container, false);
              TextView tvLoveStory=(TextView) rootView.findViewById(R.id.textView1);
              TextView tvTmyName=(TextView) rootView.findViewById(R.id.textView2);
              return rootView;
       }
}

Your project may show errors , so simply clean project errors will go off.

Step-6- Now Create TabsPagerAdapter.java to hold the child fragments on parent.
Extend this class by FragmentPagerAdapter and add unimplemented menthods.

 TabsPagerAdapter.java

package com.allandroidprojects.musicplayer;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter{

       public TabsPagerAdapter(FragmentManager fm) {
              super(fm);
              // TODO Auto-generated constructor stub
       }

       @Override
       public Fragment getItem(int index) {
              //Return child fragments
              switch (index) {
              case 0:
                     // Albums fragment activity
                     return new AlbumFragment();
              case 1:
                     // Artists fragment activity
                     return new ArtistsFragment();
              case 2:
                     // Songs fragment activity
                     return new SongsFragment();
              }
              return null;
       }

       @Override
       public int getCount() {
              // Return no of tabs
              return 3;
       } 
}

Step-7: Define the logic of tabs and swip actions in MainActivity.java
          Extend this class by FragmentActivity implements ActionBar.TabListener and add unimplemented                  methods.If file is giving errors then add this on top:
      import android.app.ActionBar.TabListener;

Final Code:

MainActivity.java

package com.allandroidprojects.musicplayer;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

       //Declare the components used
       private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
   
 // Tab titles
    private String[] tabs = { "Albums", "Artists", "songs" };
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              // Initilize components
           viewPager=(ViewPager) findViewById(R.id.pager);
           mAdapter=new TabsPagerAdapter(getSupportFragmentManager());
           actionBar=getActionBar();
          
           viewPager.setAdapter(mAdapter);
           actionBar.setDisplayHomeAsUpEnabled(true);
           actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
          
           // Adding Tabs and clicking functionality
           for(String tab_name:tabs){
              actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
           }
          
           /**
         * on swiping the viewpager make respective tab selected
         * */
           viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    
                     @Override
                     public void onPageSelected(int position) {
                           // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);                   
                     }
                    
                     @Override
                     public void onPageScrolled(int arg0, float arg1, int arg2) {
                           // TODO Auto-generated method stub             
                     }                   
                     @Override
                     public void onPageScrollStateChanged(int arg0) {
                           // TODO Auto-generated method stub             
                     }
              });
          
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }

       @Override
       public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
              // TODO Auto-generated method stub
             
       }

       @Override
       public void onTabSelected(Tab tab, FragmentTransaction arg1) {
              // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
             
       }

       @Override
       public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
              // TODO Auto-generated method stub
             
       } 
}

Step-7: Save the project, clean and run . You can see the tabs views by swiping as below screens.



Please feel free to comment for suggestions or doubts.
Thank You !!