My previous article explains about Android Tab Layout and it got very good ranking in search engines. But unfortunately TabHost is deprecated by android in favor of fragments. So it is suggested that use fragment to achieve tab layout.

This article shows you how to create tab layout using fragments and viewpager. Also you can swipe between tab view as it is the functionality of viewpager which is not possible when using TabHost.

Android Tab Layout with Swipeable Views

Android Material Design Tab Layout

Although this article explains the Tab Layout in well detailed manner, lot of the methods used this article were deprecated. I strongly suggest check out the latest article Android Material Design Tabs (with Android Design Support Library) once you are done through this article.

ViewPager and Fragments

Before getting into this tutorial it is suggested to have knowledge on Fragments and ViewPager as these two are main concepts used here. Unfortunately I haven’t covered about fragements and viewpager on androidhive πŸ™

Layout Overview

Checkout the following pic which explains the complete overview of layout architecture. Basically we are using ViewPager as main layout and for individual pager views we use Fragments. The tabs are part of Action Bar.

android tab layout with swipeable views

Creating new Project

Even though you are not familiar with ViewPager or Fragments, don’t worry. You will get an idea about what those are and how to use them once you are done through this article. So let’s start by creating a new project.

1. Create a new project in Eclipse from File β‡’ New β‡’ Android β‡’ Application Project. While creating the project select the app theme which has Action Bar as shown in the below image.

android tabs with swipe gesture

2. As we are going to use Fragments, extend your main activity from FragmentActivity. Also implement this class from ActionBar.TabListener as we are adding Tabs too.

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {

3. Open main activity layout file and add ViewPager element. (My layout file for main activity is activity_main.xml)

<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>

4. I normally prefer to create a separate package for adapter classes just to separate them from activity classes. So create a new package named your_package_name.adapter. I named my new package as info.androidhive.tabsswipe.adapter

5. I am creating a FragmentPagerAdapter class to provide views to tab fragments. Create a class called TabsPagerAdapter.java under adapter package. This adapter provides fragment views to tabs which we are going to create them later in this tutorial.

package info.androidhive.tabsswipe.adapter;

import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
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);
	}

	@Override
	public Fragment getItem(int index) {

		switch (index) {
		case 0:
			// Top Rated fragment activity
			return new TopRatedFragment();
		case 1:
			// Games fragment activity
			return new GamesFragment();
		case 2:
			// Movies fragment activity
			return new MoviesFragment();
		}

		return null;
	}

	@Override
	public int getCount() {
		// get item count - equal to number of tabs
		return 3;
	}

}

Adding Tabs to Action Bar

6. In order to display tabs we don’t have to use any other UI element like TabHost. Action bar has the inbuilt capability of adding tabs. All we have to do is enable it using setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) method. Open your MainActivity.java do the following.

Here I am adding three tabs Top Rated, Games, Movies to action bar. So I just stored all the tab names in a String array and added them to action bar using a for loop.

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {

	private ViewPager viewPager;
	private TabsPagerAdapter mAdapter;
	private ActionBar actionBar;
	// Tab titles
	private String[] tabs = { "Top Rated", "Games", "Movies" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Initilization
		viewPager = (ViewPager) findViewById(R.id.pager);
		actionBar = getActionBar();
		mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

		viewPager.setAdapter(mAdapter);
		actionBar.setHomeButtonEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);		

		// Adding Tabs
		for (String tab_name : tabs) {
			actionBar.addTab(actionBar.newTab().setText(tab_name)
					.setTabListener(this));
		}

If you run the project, you can see the tabs displaying under action bar.

android action bar adding tabs

Adding Views for Tabs

We already returned respected fragments for tabs in the adapter class. To make it simple I am creating very simple layout for each tab and leaving it to you to build your own UI depending on your requirement. For now I just displayed a label in the view with some background color.

Β» First Tab View

7. The first tab I added is Top Rated. Create a new layout file under src β‡’ res folder named fragment_top_rated.xml and paste the following code.

<?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:orientation="vertical"
    android:background="#fa6a6a" >
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Design Top Rated Screen"
        android:textSize="20dp"
        android:layout_centerInParent="true"/>
    

</RelativeLayout>

8. Also create respected Fragment activity class for this view. Create a new class named TopRatedFragment.java under your main package.

package info.androidhive.tabsswipe;

import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TopRatedFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
		
		return rootView;
	}
}

Β» Second Tab View

The second tab in the list is Games. Just like above create a layout file and activity file for this tab.

9. Create a new layout file under src β‡’ res folder named fragment_games.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:orientation="vertical"
    android:background="#ff8400" >
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Design Games Screen"
        android:textSize="20dp"
        android:layout_centerInParent="true"/>
    

</RelativeLayout>

10. Create a new class named GamesFragment.java with following code.

package info.androidhive.tabsswipe;

import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class GamesFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_games, container, false);
		
		return rootView;
	}
}

Β» Third Tab View

This third tab is Movies. This one need a layout file and activity class.

11. Create a layout file called fragment_movies.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:orientation="vertical" 
    android:background="#17df0d">
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Design Movies Screen"
        android:textSize="20dp"
        android:layout_centerInParent="true"/>
    

</RelativeLayout>

12. Also create activity class for this view named MoviesFragment.java

package info.androidhive.tabsswipe;

import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MoviesFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
		
		return rootView;
	}

}

Run the project and check whether the views for tabs are added or not.

Android Tab Layout with Swipeable Views

And this is how it looks in landscape mode

Android-Tab-Layout-with-Swipeable-Views-landscape

Tab Change Listener

If you run the project you can see the swiping views working, but if you select a tab, view won’t change automatically. This is because ViewPager didn’t know about the tab change event. We have to manually change the view using Tab change listener.

13. In your MainActivity.java class add following code.

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

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

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

View Change Listener

14. As well if you swipe the view, you can’t see respected tab selected. Here also using ViewPager setOnPageChangeListener() we have to select the respected tab manually.

		/**
		 * 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) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

After adding these two listeners, if you run the project you can see everything working good.

Complete Code

Below is the complete code for MainActivity.java class

package info.androidhive.tabsswipe;

import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import info.androidhive.tabsswipe.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {

	private ViewPager viewPager;
	private TabsPagerAdapter mAdapter;
	private ActionBar actionBar;
	// Tab titles
	private String[] tabs = { "Top Rated", "Games", "Movies" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Initilization
		viewPager = (ViewPager) findViewById(R.id.pager);
		actionBar = getActionBar();
		mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

		viewPager.setAdapter(mAdapter);
		actionBar.setHomeButtonEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);		

		// Adding Tabs
		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) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

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

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

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

}
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Khalid Ibrahim

    You have got the best Android tutorial blog in the whole internet. Android Dev is an exception. Thank you and stay informative, man!

  • Phuc Nguyen

    Nice article!

    Ah, May you let me know the name of the software that you use to make the figure image at Layout Overview session?

  • siddhu
  • siddhu

    Not working at api version 8 check it

    • Raed Marji

      its not supposed to, the action bar was introduced after API11 so I suggest you use Sherlok Action bar library if you want to support versions down to 8.

    • Vivek

      No.. There must be some way out. IM working on same. Will let U know.

    • Vivek

      Try using FragmentTabHost with Fragment ..
      It’s working great.

  • vivek

    First of all thanks for your quick reply on my request.

    Now if I need to start a new activity say new fragment from with in same fragment on click of a button. how could we do that.

    Thanks.

    • Just start the activity from fragment class. Place a button in fragment_games.xml and write activity launch code in GamesFragment.java and test

      • Vivek

        Hi Ravi,

        I was not specified with my question.. πŸ™

        Exactly what I need to know is undermentioned ::

        Say I have 3 tabs –> Tab1 / Tab2 / Tab3.

        Considering Tab1 –> Here I have Fragment class Say GamesFragment.java. This Fragment class have a button. Now when I click on button I need to replace fragment_games.xml with fragment_cricket.xml with it’s corresponding class CricketFragment.java.

        Note* :-> This fragment_cricket.xml still exists in Tab1 … i.e. I need all tabs through out application while replacing fragments.

        I will be thankful to you if you could manage your time for this. Really stuck on this.

  • This is a best blog for Android Developer. Thanks you so much.

  • Piotr Denc

    great tutorial !
    But I have a question
    how to change TextView in fragment from Activity ?

    • Despro Despro

      you can using obsever patern for to do this.

  • Saurabh Pandya

    Can we add the view above tabs?

  • Guest

    ActionBar.TabListener is not implementing to my MainActivity class

    • What do you mean by not implementing.

    • Vivek

      Just try clean and built your project. There’s nothing wrong in the given code. Else it is not compatible with lower api’s.

      Hope it helps.

  • Adhamsheriff

    Hi,
    Thank You For Your Tutorial.
    But I don’t need action bar in above project, what i have to do for that?

  • faraz

    nice post!! nice webSite!!

  • Alex

    Hi, can i use ListView with TopRatedFragment.java for example? findViewById is not working here.

    • nirmal

      Hey Did u got any solution for list view
      ?

    • A

      use getView()

      ListView lv =(ListView)getView().findViewById(R.id.list);

  • Nilachandan Mohanty

    Sorry for a very basic question. But how to add ViewPager from eclipse palette? I am not finding one.

  • Fauzi

    i’m doing exactly same with this tutorial, but i have a problems with TabsPagerAdapter.java

    an error occur at the fragment, and it said “Type mismatch: cannot convert from SensorFragment to Fragment”

    what’s i’m missing?

  • Phuc Nguyen

    It worked for me! Thanks so much.

  • Nilson Silva

    Hi nice tutorial congrats…

    but I have a doubt how can I put some data in the layout i.e. “Top Rated” ?

  • Felix

    Thank you so much! Awesome Example/Tutorial.

  • yesid

    Hello, excellent tutorial, it took me two days looking for a tutorial to serve me and this was the best.

    but I have a question, as I can do so that when you turn the screen redraw is closed at this time the app to rotate the screen.

    sorry for the English, is google translator

  • Tulai Paul

    Excellent article that unravels Viewpager and tablayout. Such articles will surely inspire millions of mobile apps and games developers who have been providing with newer versions to the leading mobile ad network companies like revmob, chartboost, adcolony, appnext and others

  • Amit

    Hi Ravi, another awesome tutorial, really helpful

    May i know how to show text like this : Top Rated instead of TOP RATED

  • nirmal

    How to add custom List View in this?? it is giving error

  • kevin

    can i add a button in one of the tab and link to another page?

    • nirmal

      ya
      u can add button

  • Aleksei

    This is great! Thanks a lot! You saved my day

  • Dan

    Followed to the letter this tutorial but cannot get past step #2. I’m getting “ActionBar cannot be resolved to a type”.

    I tried modifying the manifest file to select a minimum of API 11 (per the suggestion) and rebuild my project.

    I’m still getting that error. Otherwise, looking forward to this tutorial as I needed such an enhancement for my project.

    • Manny264

      Type this in within import statements: import android.app.ActionBar;
      import android.app.ActionBar.Tab;

  • alex

    Thank you, it was a mess before. Now it is much clearer.

  • nirmal

    how to change title ,i want to change title to my custom title …

  • Pari

    I’m getting “The method onTabSelected(ActionBar.Tab, FragmentTransaction) of type MainActivity must override or implement a supertype method” . please help me!

  • Pari

    And Also “The type MainActivity must implement the inherited abstract method ActionBar.TabListener.onTabSelected(ActionBar.Tab, FragmentTransaction)”

  • Viamat

    Hi Ravi,
    Thanks 100 % for this tutorial.

    But here is my big challage:….. even “Nirmal” asked about it!

    How to put Expandable list views within the fragments:
    that is:
    ExpanbableListView in Top-rated
    ExpanbableListView in Games
    ExpanbableListView in Movies.

    I tried many ways!! but my TabAdapterClass always gets this error:

    – Type mismatch: cannot convert from Top-rated to Fragment.
    – Type mismatch: cannot convert from Games to Fragment.
    – Type mismatch: cannot convert from Movies to Fragment

    Please Ravi or anyone….. interested in helping me overcome this challenge. Please in box me kwevany@gmail.com

  • Guest

    Hi Ravi,

    Firsdt of all a very nice tutorial

  • Arn

    Hi Ravi,

    First of all a very nice tutorial. I have been following Androidhive since very long. I have created tabs as per http://www.androidhive.info/2011/08/android-tab-layout-tutorial/ Since TabActivity is deprecated from API Level 13, I want to know how can I change my code to integrate FragmentManager to achieve the same results.

    Thanks for your help…

  • Fred

    I was trying to get it from Android docs… not so clear, not so easy
    Thanks a lot.

  • Thank you for this clearly structured description, fantastic

  • Adhamsheriff

    Hello,

    I want to change tab color and tab text color?
    How i want to implement that?

    • Vivek

      Try this … Hope it helps πŸ™‚

      Here tabHost is TabHost… In case of fragment this would be FragmentTabHost.

      Also ..
      Not sure for ActionBarTabs.

      ——————– code ——————————

      for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)

      {

      TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);

      tv.setTextColor(Color.WHITE);

      tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#765433"));

      }

      tabHost.getTabWidget().setCurrentTab(0);

      tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#8c6b48"));

      }

  • Ugur Cakmak

    Thank you for this great tutorial. Also works flawless with ActionBarSherlock !!!

  • Romain

    Awesome tutorial, thanks.

  • Eli

    Great tutorial, was really helpful. How can I include a webview in the fragments instead of the textview?

    • Vivek

      Same as U do using activity. There’s nothing change in fragment than activity else fragment provide an easy way to replace view’s.

  • Qt

    I’ve added lists and I’m struggling with adding action listeners to the list how can i go about this?

    • Vivek

      Specify your question what exactly U did and what exactly U require.

  • Lee Nguyen

    Hi You,

    I want to ask, for example, is rated one tab button in, press the button to move through the tab Game Sharing, which I could not get through it, and then sharing transfer functions like, thank you very much

  • AK

    i have page with listView…but not working……Any Proper Suggestions

    • Kingto So

      Me tooooooooo!
      I’ve tried did this with ListView in each ViewPager (Tab).
      But what I got was the list items didn’t respond to my touching, like out of focus.
      Please help

  • Erando

    Thanks for this tutorial. But I struggle at step 6. Everything is set as you described it, no Errors from Eclipse. But when I run the app it crashes and my logcat says: http://pastebin.com/WYTTQzAQ
    NullPointer doesn’t really help a lot… do you know what could be wrong? As I sad, my MainActivity and the corresponding xml file are just as yours.

  • mohammadreza

    nice Ravi . please teaching android server database programming. and make a example . like a Market app that working with server database.

  • dominic smith

    nice one, i’m having trouble getting button clicks to pass from the fragment to the activity to play a sound on click. Any tips? i’ve tried the following with a “buttonPressed” tag in my xml for my fragment. but so far no good. thanks

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_traditional, container, false);

    //******************getting button clicks*******************
    Button a = (Button) rootView.findViewById(R.id.button1);
    a.setOnClickListener((OnClickListener) this);
    //**********************************************************

    return rootView;
    }
    //******************getting info from xml tagline “onClick= buttonPressed”

    public static void buttonPressed(View v) {
    switch(v.getId()){
    case R.id.button1:
    System.out.println(“button1”);
    break;
    }
    }

  • David

    hi!

    i’m using this and it’s very good.

    But i want to make an exit if the back button pressed in 2sec.

    How can i manage that and which class should i put it in?

    before using fragments i’m did it this way:

    private static final long DOUBLE_PRESS_INTERVAL = 2000000000;

    private long lastPressTime;

    public void onBackPressed() {

    // Toast.makeText(getActivity(),

    // Resources.getSystem().getString(R.string.kilepes_dupla),

    // Toast.LENGTH_SHORT).show();

    long pressTime = System.nanoTime();

    if (pressTime – lastPressTime <= DOUBLE_PRESS_INTERVAL) {

    // this is a double click event

    System.exit(0);

    }

    lastPressTime = pressTime;

    }

  • moon

    Hi Sir, i try to download the code and implement it in my project, however there is a lot of errors. – like ActionBar cannot be resolved to a type. how do i remove those errors ?

    • You have to keep the android version above 3.0

      • moon

        hi, my android version is 4.3. do i need to create additional files on top of those given ?

        • orangedusk

          Did you try setting the minimum sdk version to 11 in the manifest file?

          • Fred Sousa

            weirdly enough it gives this error and doesn’t suggest importing actionbar but you can.

            use import android.app.ActionBar;

  • a-ssassi-n

    http://www.androidhive.info/wp-content/uploads/2013/10/Tabs-Illustration.jpg
    Hey admin.
    Which tool did you use to create this image.

  • Tobi

    How can I change the Fragments used in each Tab? For Example: Tab 1 has its default Fragment A. Fragment A has a button which calls Fragment B. If it is pressed, Fragment A disappears and Fragment B appears. All in the same tab.

    How can this be done?

    • Akhila P

      For each tab You ll b having a class file no??
      Create an interface and in the MainActivity along with the
      “implements Actionbar”.TabListener” append this too ” ClassName.Interface” followed by a comma ( , )

      then Pass a reference through that interface and in that interfaces method with the help of fragment manager replace the Fragments

      • Naguib Ihab

        Hi, I didn’t really understand the second part? Can you please explain further, or with an example? Thank you

    • mahdi

      how can you change fragment with button call ?

  • ugarte

    Hello! I think that the article which you have written is fantastic!
    I would like to consult a doubt. I am developing an application and I have a little problem with it. How could I combine the navigation of the tabs with the navigation drawer?
    I have an ActivityMain that it extend to ActionBarActivity with navigation drawable. I would like to do that if you choose a determinate Fragment, it will do aΒ  different Tabs with Swipeable Views.

    Thank you very much. I wish someone has a break for answer me. Sorry, I don’t speak English very well.

    • Hi Ugarte,

      As per android docs, the suggested way is not using Tabs when your app has navigation drawer. You should use only one of them.

      • ugarte

        Thank you for your answer. I don’t found the way to do it but, It has to be possible to do it because many applications use it. For example, Google Play, Play Games, Play Books…

        I divide the information with Navegation Drawer and I divide that information in categories with the Tabs.

        Thank you

  • Mira Series

    Hi Ravi,
    Your web is great, keep it up !
    I managed to add a webview to a fragment and to keep its state after switching fragments ( using myWebView.saveState(webViewBundle); in onpause method and restoring it )
    But it’s working slow. It took like 3 seconds to switch back the fragment with the webview (Running in Atrix 2)…
    I’ve been searching but i haven’t found anything about it except this http://stackoverflow.com/questions/19925776/android-webview-restore-state-pretty-slow , same problem with no answers.
    Is this normal ? Do you have any suggestion?

    Thanks in advance
    Gabriel

  • Mae Lumpay

    Hi. This is a great help in my project but when i run my project it stopped. Can you help me with this? Seriously im a beginner in android.

  • zeto

    Can you make a tutorial on how to communicate between fragments and the activity?

  • Guest

    Hi ! I’ve looked this a lot on Internet, but there’s not something as complete as this article. I’m very grateful Ravi Tamanda.

    I’m new in Android Programming and I have a doubt, supose I have two buttons defined in the fragment_top_rated.xml, how can I change the layout of this Fragment (only this fragment) from TopRatedFragment.java when pressing a button?

    Thanks for attention !

  • John Anders Murillo

    Hi ! I’ve looked for this (Tabs+ Swipe Views) a lot on Internet, but there’s not something as complete as this article. I’m very grateful Ravi Tamanda !

    I’m new in Android Programming and I have a doubt, supose I have two buttons defined in the fragment_top_rated.xml, how can I change the layout of this Fragment (only this fragment) from TopRatedFragment.java when pressing a button?

    Thanks for attention !

  • SMZ

    Hi, How to pass variables to tabs from MainActivity?

  • Donald Lee

    First of all, This is the best tutorial I could find related to tabs + fragment + ViewPager, thank you so much. Just one more question to ask, how could I get the currently working fragment? I have tried several ways but seems I couldn’t get the control of the showing fragment. This may sounds a bit confusing. for instance, A non-static variable created and initialized inside fragmentA.

    public class Setting extends Fragment implements OnClickListener{
    private final String TAG = “Setting”;
    private Activity activity = null;


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.i(TAG, “onActivityCreated”);
    activity = getActivity();
    findView();
    initial();
    }

    public void getActivity(){
    activity.runOnUiThread(new Runnable(){

    });
    }

    So if I run fargmentA.getActivity(); The variable “activity” will throw nullpointerexception.

  • Rabar

    Hi , Thanks for you fantastic tut , but I have only one question
    how to make second tab default tab ? or how to change selected tab programaticaly?!

    • You can use this code to make a tab selected
      actionBar.setSelectedNavigationItem(1);

      • hameed

        Thanks Ravi ! Its work well fine ! i have a query how ca i trigger between fragment
        ex : fragment A contain a button, Fragment B has some view, once i click FRAGMENT A button , i need to trigger FRAGMENT B function

  • Akhila P

    Suppose i have tow diff listviews in two tabs say “GameList” in Games tab and “Movie List” in Movies Tab, Now the Question is How should i Start an Activity if i click a list item in the listview
    i was getting an error since couldn’t get the Context and can’t start new Activity
    Kindly give me how should i code the intent and initialize that…

  • Jake

    I’m looking to use this to make a fragment activity where there are three tabs: Friends, Home, Search tabs. I would like a listview where the ViewPager is. Could this be used to do such a thing? I have something working already just without tabs and with simple buttons at the top, however tabs would be much nicer.

  • Haider

    Very very Nice tutorial. Working absolutely perfect. Thanku very much πŸ™‚

  • Erqem Husaini

    Hi, Very Nice tutorial… Helped me alot
    How can I have two action bar placed above one another on top of the screen with different tabs of their own.
    Just simple Idea would be helpful
    Thank You πŸ™‚

    • Darrel Siegle

      You should be able to set this android:uiOptions=”splitActionBarWhenNarrow” When the screen is narrow (portrait in a Phone) it’ll show two rows if needed, and a single row when landscape (if it fits).

      If you want to always have two tab rows then you’ll need to use the TabHost and create a custom layout. I know the Author says it’s deprecated but it’s not, it’s just recommended in most cases to use the ActionBar, in support.v13 they added FragmentTabHost.

      http://developer.android.com/reference/android/support/v13/app/FragmentTabHost.html

  • Fazle Rabby Tanzil

    This the best tutorial anyone can have… I learned fragment and much more.. However i have few questions.. I want to support it for gingerbread api level 9, as i am using support.v4 expect it to work with api level 9.. but the action bar forcing me to use min sdk api level 14.. please help .. thank you.

  • Chethan Shetty

    Great tutorial, can you please tell me how to capture an click event inside Games or movie tabs on text view. Thanks in advance.

  • Jalpesh Vrinsoft

    hi thanks for such a nice tutorial but i want to know that how can i add tab host at bottom in this your sample code?
    plz reply me as soon as possible

    • Guest

      You’ll have to use the TabHost in order to have tabs at top and bottom.

      • sedat

        Hi all
        I tried to combine bottom tab host and this , although there is no error while debugging it stops can you help me?
        my debug stops these lines:
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        .
        .
        .
        Actually when I toggle these comment it works but no action tabs.

    • Darrel Siegle

      The standard ActionBar will not allow for this, you’ll have to use TabHost to do this, not the v4 but the v13 one if you wish to support fragments.

  • vinayak

    Hi. Thanks for this beautiful tutorial. I would like to know how to put ExpandableListView in each tabs. It would be helpful if you provide example on the same.

  • John

    I am very new to this so I am wondering how to add list inside of one tab? Could you give me some help?

  • De

    In the switch statement in the TabsPagerAdapter class, eclipse is not able to return the Fragment because the class is not specifically a Fragment. I have a “Type Mismatch”.

    Any ideas how to alleviate this or if I’m doing something wrong?

    • De

      I tried casting it to a fragment but it doesn’t work.

      • sdfsf

        extend Fragment in the class that is being called

    • De

      I’ve figured it out. My Fragment classes were importing android.app.Fragment vs. the support.v4.app.Fragment version.

  • GeneralKimi

    Thanks… But, min SDK is 11 not 8…

  • vinayak

    Hi,

    I am not able to run this on android 2.3 or high mobiles.
    How can we support on android 2.3 or high mobiles.

    • khushwant

      Hi,

      You need to use android support library and also android-support-v7-appcompat to make it work.

      Thanks

  • Krzys

    Hi. Can anyone show way to send data from FragmentActivity to Fragment? I created Tab with this tutorial and now I’m trying to send String between activity and fragment.

  • vignesh

    Hi this tutorial is very helpful. I need a suggestion that how can we change the orientation when clicking the particular tab and hide the action bar. And come back to portrait view by clicking a button.

  • damai007

    Hi, I actually mixing this post with http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
    In my case, in main Fragment Activity, I have to run AsyncTask class first to get json data before invoke onCreate, because I want to change textview in another fragment based on information from that json. Is there any ways to do it?

    If I run “new MyAsyncTask().execute()” in “onCreate()” (without the quotes) in main Fragment Activity, all fragments are loaded up and then execute the MyAsyncTask. I have searched on internet how to invoke a class AsyncTask before invoking onCreate, but I found nothing.

    I really need your suggestion. Thanks.

  • Fattouh92

    Great tutorial. very easy to follow

  • sedat

    Hi this tut is very helpful for me. But I am trying to combine this with footer tab.(I have 3 tabs in footer and I wanna make one tab’s content like this), there is no error but while debugging it stops. When I looked debug way it stops when start this main. I deal 7-8 hours but I cannot found nothing. Can anybody help me?

    • sedat

      my debug stops these lines:

      actionBar.setHomeButtonEnabled(false);
      actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

  • Khushwant Singh

    Hi,

    Many thanks for this article. As always, I appreciate your efforts.

    I have a question on action bar/fragments using support library. I was trying to run this project using support library V4 and V7-appcompat and in fact was able to run this project on android 2.3. Since using support library can run action Bar and other new features on older versions, then should one always use support library to use action bar and other new features? Do you know of any disadvantage of using support library in terms of performance/crash? Also do you recommend using two sets of codes, one using support library (for API 8,9 and 10) and the other for API 11+?

    Thanks,
    Khushwant Singh

  • Guru Prasad

    Hi Sir..very thankful for this tutorial ..
    1)..:- i four activitys .in each activity i have list views ..now when i am trying switch activitys by swiping its taking 2 to 3 seconds to switch the activity ..what is the reason please help me..
    2)..:-in 4 activitys i have constant header like master-page example (searching in listview) now where i have to write code ..i mean A , B ,C ,D are my Tabs and “Z ” is my main activity …please help me ASAP..thanks in advance

    • Babar

      hi Guru Prasad
      plz tell how you add list view in under of the tab??
      i have try this i can’t..i am using display list with listadapter and arrayadapter but it will generte error sp plz help me how can iadd list view under one of tab…

  • RZ

    Hi. thank you very much. I m newbie in Android Java. First tutorial about Action Tab that I can complete and run perfectly! Congratulations for the job.

  • Pablo Lunardi

    Please help! Why the ActionBar is showing below the tabs when I run the app??? It should appear above , like in the video. πŸ™

  • Micahel Panin

    Hi! i am sorry for criticizing your post. It was very helpful for me. But we are inflating our view EACH time when we are scrolling through a tab. Shouldn’t we make any caching(smth like viewholder)?

  • Cheby

    Just Perfect! Great Job

  • Leng AK

    Hi, Sir. I have a problem in this tutorial. When I put Toast to display text in each Fragment class, it shows incorrect Toast.
    How to fix it ? thx…

  • iloveyou

    Thank you. I love you

  • Soheil Afshari

    i have button on tab 1 how can i declare it or where should i put my codes ?

    • Leng AK

      public class TopRatedFragment extends Fragment {

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

      View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
      yourButton = (Button) rootView.findViewById(R.id.button);

      return rootView;
      }
      }

      • Soheil Afshari

        Tanx its working .

        • Guest

          Soheil Afshari : its working, but it diplay incorrect Toast

      • Babar

        hi Leng AK
        plz tell how to add list view in under of the tab??
        i have try this i can’t..i am using display list with listadapter and arrayadapter but it will generte error sp plz help me how can iadd list view under one of tab…

        • Leng AK

          hi Babar please wait, I will test it first.

          • Babar

            ok thanks for replying Leng

          • Babar

            Leng AK if you test it so plz tell me….

        • Leng AK

          yes, but now i’m busy much

          • Babar

            thanks Leng i have do but thanks

      • Mahdi

        Hi , is it possible to change pager and tab with button event ? not with swipe

        i use this code but it return error and force close

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View v = inflater.inflate(R.layout.activity_checkout_method__fragment,

        container, false);

        pager = (ViewPager) v.findViewById(R.id.pager);

        pager.setAdapter(new ViewPagerAdapter_PlaceCartOrder(getFragmentManager()));

        btn_continue = (Button) v.findViewById(R.id.button_continue);

        btn_continue.setOnClickListener(new OnClickListener() {

        @Override

        public void onClick(View v) {

        // TODO Auto-generated method stub

        //Replace right fragment with another fragment

        //pager.setCurrentItem(2);

        }

        });

        return v;

        }

  • Jared Amul

    How can i position the tabs at the bottom???

  • Samuel Tang

    Hi, May I enquire:
    How do we pass data between fragments

  • Ahmet G

    Hi, could u please help me to change “indicator color” which has been set blue as default? I want to change the tab bar indicator color to different color. Is that possible?

  • Hai

    Hi everyone, i’d like to add a listview on each tab. Please show me how, thanks!

    • spiralni

      Just declare it into each fragment_*.xml

  • spiralni

    How can implement the TabListener for older devices.. It is not in the support package

  • Millamber

    Thanks for a great tutorial, working magnificently.

    I have one issue. I have a preferences activity that I use to determine which tabs will be shown which seems to work ok, but when I return to this activity, the wrong view is shown on the tab despite the adapter being updated and calling notifydatasetchanged.

    Any ideas, can post code if required.

    TIA

    Millamber

  • NewBieAndroid

    how to pass value from MainActivity to Fragment?
    help me plsssssss

    • NewBieAndroid

      i pass value from loginActivity to MainActivity
      but, i wanna use that value each fragment
      wat should i do

    • Dilip Kumar N

      You can access the MainActivity objects from Fragment using getActivity() method

  • chetan

    I am very new to this so I am wondering how to add list inside of one tab? Could you give me some help?

  • MyName

    I LOVE THIS PAGE IN CAPS!

  • Blas

    Great tutorial!

  • MehdiB

    Awesome ! Worked like a charm πŸ™‚ From now, I’m following your website πŸ™‚

  • SP

    I have 3 activities. Now I want to tab layout to show this 3 activities when I click on a one of the 3 options from the action bar. How to do that ?

  • Vutka Bilai

    very helpful tutorial . I followed through all the tutorial . But I’m a newbie in android development , can I load listView in a fragment ACTIVITY , I mean i want to load some shared Preference data show it in a fragment view like each tab will show some data represented in a list view . can I do that in a fragment view . PLZ hepl ?

  • n4ssim

    The tabs work well. However, how would I be able to replace the layout from a tab with a new one, say if i click on a button? Would really help if I’d know how to get this done

  • Vijay

    Hello Ravi,
    First, thank u so much for a really great tutorial for noobies like me to understand. I used your code in my mini project and am now stucked at a point. Google’d a lot but still helpless so finally have to disturb you.
    what i have done is-
    1.I have implemented a webview in TopRatedFragment.
    2.Plz tell me how to use onKeyDown with this fragments.
    3.It should be in a way that when i press back-key it should check whetther the webview can go back or else should give a alert for exiting.

    Please please help!

  • Venubv

    Hello Ravi,
    Is there a way to add a bottom bar for each tab page and the bottom bar should be unique for each tab.

    Regards,
    Venu.

  • Babar

    Hello Ravi,
    how can i add list in under one tab??
    i will try this using listadapter and array adapter but its generte error,so plz give an example in which add list in under one of tab plz…

  • priya

    Hello Sir,
    Your tutorial is very helpful.
    How to add icons instead of title in tabs?
    I tried with seticon() but i couldn’t figure out correctly.

    Thanks&Regards,
    Priya.

  • Commenter

    My problem is after I extend fragment on some tabs than I want to use Activity which I cannot do. Because Fragment is already extended and I cannot extends Activity anymore. So what shall I do?
    I after extending fragment I want to use activity also.

  • zeto

    When you press the slide button it doesn’t do anything. What should be the code for this kind of listener?

  • Biraj Das

    Hi

    I was able to complete this project.
    I am working on an App that requires to fetch data from a web service in form of json.
    i followed your previous example and did that also. till here everything is fine.
    Now i want to show this data on swipe of tab. this also happens but the data is shown in a different screen and you have press back to come back to the swipe able screen.
    Any suggestions

  • Thasan

    Under the Fragment wants to make a list with json. How do I do that?

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_movies, container, false);

    return rootView;
    }

  • Kevin

    Thank you so much for this. It was so simple, it only required a bit of learning to move all my application logic from the Activity to the Fragment.

  • TheProgrammingFreakFreak

    Very gold tutorial thanks πŸ™‚

    • TheProgrammingFreakFreak

      *good

  • Masha

    Really cool tutorial. I have a gridview.xml with images in each view. How do i set them up in java yet the class extends Fragment..while i need Activity?

  • janith

    Janith Udara

  • shubham

    Great Article.

    But i’m stuck with one problem.

    When i’m trying to run the activity in full screen then it crashes.

    i’m adding android:theme=”@android:style/Theme.NoTitleBar.Fullscreen in manifest file.

    Is there any workaround for this problem ??

  • Jasson

    Hello i really like this… but i need to implement slide menu with this in one frgment….. but this use fragmentActivity i dony know how traslate it to fragment…….. any help

  • Sereen Shalby

    hello please can i implement this solution with activities instead of fragments?? and what will be change??

    • I’m afraid that is not supported by the Android itself. What to you need to do?

  • Maykel Matheus Dias

    Hi man, i’d like know how change the color of tabs…thanks

  • Ricardo Ferreira

    Thank you very much for your solution, it solved me a huge problem πŸ™‚

  • Guest

    hello..i am facing a problem in TabsPagerAdapter class the error is showing… “Type mismatch: cannot convert from TopRatedFragment to Fragment” and same error in all three return type can someone help me out.

  • Deepak Singh

    hello..i am facing a problem in TabsPagerAdapter class the error is showing… “Type mismatch: cannot convert from TopRatedFragment to Fragment” and same error in all three return type kindly help me out of this issue.

  • Deepak Singh

    Hello Thanks a lot.. and i figured out the issue and really great article…

    • wiliam

      how you solve it…

  • Antwnis

    Hello. I believe there is a major bug on this project let me explain. If u add a log message on each fragment you will notice that when u select Tab1 onCreateView of Tab2 is called. Another way to chech this is to add a log message on the getItem on page adapter; one message for each new Fragment. You will notice that toprated and games are created simultaneously. Too bad i havent found what causes that mistake yet

    • Mike

      Yes this happens to me too… Anyway I will try to find out….

      • Miramel

        did you find the solution ?
        if so plz post it

        • Darien

          just add

          viewPager.setOffscreenPageLimit(3);

    • Mike

      well i don’t know why but i had put the line actionBar.setSelectedNavigationItem(position) in the method onPageScrollStateChanged. Then obviously i put it in onPageSelected. I don’t know if you did the same but I think that I had to mention it….Mine malakia my friend ;)…

  • Ann_CM++

    how to send data from fragment to fragment?
    help me please

  • Cesar M. Malainho Oliveira

    It is possible to get this example to work in API 8? Thank you very much

    • AlexN

      Yes, you must use android.support.v7.app.ActionBar.TabListener, instead of android.app.ActionBar.TabListener.

      • dhnjy 18

        Do i need to add android support v7 library for the same reason?

        • Amit Kiri

          Hello, I want to use this code in API 8 .But, when i run this code in API 8 I am getting these error:

          04-18 19:28:38.926: I/dalvikvm(17337): Failed resolving Linfo/androidhive/tabsswipe/MainActivity; interface 9 ‘Landroid/app/ActionBar$TabListener;’

          04-18 19:28:38.926: W/dalvikvm(17337): Link of class ‘Linfo/androidhive/tabsswipe/MainActivity;’ failed

          04-18 19:28:38.930: D/AndroidRuntime(17337): Shutting down VM

          04-18 19:28:38.930: W/dalvikvm(17337): threadid=1: thread exiting with uncaught exception (group=0x40020648)

          04-18 19:28:38.953: E/AndroidRuntime(17337): FATAL EXCEPTION: main

          04-18 19:28:38.953: E/AndroidRuntime(17337): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}: java.lang.ClassNotFoundException: info.androidhive.tabsswipe.MainActivity in loader dalvik.system.PathClassLoader[/data/app/info.androidhive.tabsswipe-1.apk]

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1645)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1747)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.access$1500(ActivityThread.java:155)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.os.Handler.dispatchMessage(Handler.java:130)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.os.Looper.loop(SourceFile:351)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.main(ActivityThread.java:3814)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.reflect.Method.invokeNative(Native Method)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.reflect.Method.invoke(Method.java:538)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at dalvik.system.NativeStart.main(Native Method)

          04-18 19:28:38.953: E/AndroidRuntime(17337): Caused by: java.lang.ClassNotFoundException: info.androidhive.tabsswipe.MainActivity in loader dalvik.system.PathClassLoader[/data/app/info.androidhive.tabsswipe-1.apk]

          04-18 19:28:38.953: E/AndroidRuntime(17337): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:271)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.ClassLoader.loadClass(ClassLoader.java:582)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.ClassLoader.loadClass(ClassLoader.java:542)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.Instrumentation.newActivity(Instrumentation.java:1056)

          04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1637)

          04-18 19:28:38.953: E/AndroidRuntime(17337): … 11 more

          ………………………………

          So please give me solution for these error.

  • MPKr

    I want to hide the action bar but keep the tabs, “requestWindowFeature(Window.FEATURE_NO_TITLE)” doesn’t work neither do “true” because the tabs were added to the action bar. So any solution to split them away?

  • Ryan

    Tutorioal was great but when I swipe through the tabs the app crashes any ideas on what to fix?

  • JotaPardo

    Muchas gracias por este excelente tutorial, me ha servido muchΓ­simo! y he logrado entender mucho sobre esta forma alternativa a los anteriores Tabs de Android!

  • Dewi Jones

    awesome
    thanks

  • burak

    Hello,

    there is something wrong in this code. When I pass Top Rated to Games and Games to Movies, there is no problem because each one is chosen for the first tiem(i.e. onTabSelected is called for each one)
    but the problem is, when I come back to Games from Movies, or Top Rated from Games, the UI freezes. I suppose the problem is onTabReselected and onTabUnselected methods are empty. Am I right, or is there another problem?

  • Alex Abraham

    Thank you so much!!!!!!

    This really improved the UI of my application πŸ™‚

    I had a little bit of trouble adding a menu button at the top of my application once switching over to fragments but I ended up using setHasOptionsMenu(true) inside onCreate() of fragment and it worked like a charm! The menu button even disappears when swiping between activities

  • Rishul Matta

    thanks a lot…was really helpful

  • I’m facing ClasscastException when i’m runnnig. Please do find me solution. Thanks.

  • Ravi Ranjan

    How to add icons in each tabs.

    • Mukesh Kumar

      you can set Tab icon as

      // Adding Tabs
      for (String tab_name : tabs) {
      actionBar.addTab(actionBar.newTab().setText(tab_name).setIcon(R.drawable.drawable_id)
      .setTabListener(this));
      }

      • B.rohit Nare

        How can we change text size ? IS there any other option to change text font and size

  • Eric

    Best tutorial I’ve seen on tabs. Very clean code, well organized and good naming conventions.

  • Ankit Aggarwal

    Really nice tutorial. But I have a doubt. I had developed an app using TabHosts, it had Activities. Now when I implement ActionBar, can I use the same aCtivities instead of Fragments, as it would require a lot of change in code. If yes, then how?

  • Roger

    Anyone else get an IllegalStateException accessing the fragments after rotating the screen using this method?

    E/AndroidRuntime(16841): java.lang.IllegalStateException: Fragment Home{4141a1d0} not attached to Activity

  • Wojciech

    Great tutorial, I am using it in my project. Thanks for Your work. However I have a problem with replacing the fragments. How to replace any of the fragments with the new one – for example replacing the Games fragment with ‘Best adventures games” fragment. I got stucked with this. Can You please help me.

  • hajdi

    hello. it works and it helped me a lot, but i wonder
    When i turn my screen, actionBar and actionBar tabs are in the same line. Is it posible to change that so the title(action bar) will be always on top and tabs will always be on bottom? If there is a solution for that please share it with me.

  • Britman

    This is working fine in AVD ,But not in the device ? How to fix it ?.
    I used galaxy s3 for testing.
    please help.

  • Amit Kiri

    Hello, I want to use this code in API 8 .But, when i run this code in API 8 I am getting these error:

    04-18 19:28:38.926: I/dalvikvm(17337): Failed resolving Linfo/androidhive/tabsswipe/MainActivity; interface 9 ‘Landroid/app/ActionBar$TabListener;’

    04-18 19:28:38.926: W/dalvikvm(17337): Link of class ‘Linfo/androidhive/tabsswipe/MainActivity;’ failed

    04-18 19:28:38.930: D/AndroidRuntime(17337): Shutting down VM

    04-18 19:28:38.930: W/dalvikvm(17337): threadid=1: thread exiting with uncaught exception (group=0x40020648)

    04-18 19:28:38.953: E/AndroidRuntime(17337): FATAL EXCEPTION: main

    04-18 19:28:38.953: E/AndroidRuntime(17337): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}: java.lang.ClassNotFoundException: info.androidhive.tabsswipe.MainActivity in loader dalvik.system.PathClassLoader[/data/app/info.androidhive.tabsswipe-1.apk]

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1645)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1747)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.access$1500(ActivityThread.java:155)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.os.Handler.dispatchMessage(Handler.java:130)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.os.Looper.loop(SourceFile:351)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.main(ActivityThread.java:3814)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.reflect.Method.invokeNative(Native Method)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.reflect.Method.invoke(Method.java:538)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at dalvik.system.NativeStart.main(Native Method)

    04-18 19:28:38.953: E/AndroidRuntime(17337): Caused by: java.lang.ClassNotFoundException: info.androidhive.tabsswipe.MainActivity in loader dalvik.system.PathClassLoader[/data/app/info.androidhive.tabsswipe-1.apk]

    04-18 19:28:38.953: E/AndroidRuntime(17337): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:271)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.ClassLoader.loadClass(ClassLoader.java:582)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at java.lang.ClassLoader.loadClass(ClassLoader.java:542)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.Instrumentation.newActivity(Instrumentation.java:1056)

    04-18 19:28:38.953: E/AndroidRuntime(17337): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1637)

    04-18 19:28:38.953: E/AndroidRuntime(17337): … 11 more

    ………………………………

    So please give me solution for these error.

    • Tony

      This may not help you, but maybe it will help others who want to use this functionality in lower API’s. There is a built in support library that makes it work in as low as API 7, and only requires a few changes in MainActivity.java:

      1. extends ActionBarActivity instead of extends FragmentActivity (you will need to import android.support.v7.app.ActionBarActivity)

      2. change your imports to look like
      import android.os.Bundle;
      import android.support.v4.app.FragmentTransaction;
      import android.support.v4.view.ViewPager;
      import android.support.v7.app.ActionBar;
      import android.support.v7.app.ActionBar.Tab;
      import android.support.v7.app.ActionBarActivity;

      3. actionBar = getSupportActionBar(); instead of actionBar = getActionBar();

      I think that was all I had to do to get it to work in API 7 for me!

      • M Luthfan Mursyidan

        not work :(. I still got classnotfound exception.
        maybe something wrong?
        I import libs as android said, android-support-v7-appcompat.jar

  • kamil

    how set FLAG_ACTIVITY_CLEAR_TOP?

    i have exeption with this:
    Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
    ComponentName cn = intent.getComponent();
    Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
    startActivity(mainIntent);

  • Luis Ruiz Figueroa

    something I do not understand is, like the open layout mainactivity know?

    • kamil

      yes,
      i want open new login activity, and hide tabs.
      i used this:
      actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

      but this is bad way

  • kamil

    i want open new login activity, and hide tabs.
    i used this:
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

    but this is bad way, any idea how open new activity?

  • rags

    nice tutorial .. very useful

  • bij

    how to show the tab bar at the bottom?

  • smnpl

    Great guide, works fine for me. One question though, which I did not solve yet myself:
    I want to update data within the tab’s views, but I am not able, to access the views somehow, triggered from the activity.

    My thought, on how to do that:
    – The Viewpager now contains the tabs
    – I tried, saving the new Fragement() in ViewPagers getItem()-method into an ArrayList, within in the ViewPager object
    – From activity I can then call viePager.fragmentArray.get(index) …

    – That successfully gives me a reference to the Fragment
    – But on that executing getView() returns NULL … No clue what to do about that.

    So, is my approach correct? If so, what am I missing? If not, what would be a proper approach?

  • rafal

    Hi,

    I want to change text e.g. on “Top Rated” tab. I’m using

    TextView textView = (TextView) rootView.findViewById(R.id.textView1);
    textView.setText(“text”);

    in onCreateView(…) method and application crash. Any suggestions?

  • manuel

    hello, this is a particular question… how did you make the sketch for the layout it is pretty cool!

  • let_me_know

    i want open new login activity, and hide tabs.
    i used this:
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

    but this is bad way, any idea how open new activity?

  • brian56

    Hi Ravi,
    You’ve made a great tutorial. But I want to work more with fragment, such as saving state of each fragment, or pressing back button to go to previous fragment.
    Can you made more tutorials about fragment to provide us a typical approach to work with fragment more professionally and correctly?
    Anyway, thanks for all of your tutorials, they’re really great.

  • Aliya

    Great Tutorial, everything works fine!!! thank u so much!

  • Mukesh kumar

    Hi Ravi,

    This tutorial is very nice, but I’m getting following error.

    In TabsPagerAdapter.java I’m not able to create object for my fragments ex

    switch (index) {

    case 0:

    Fragment f=new UpdatingSitesFragment()
    return f;

    // here UpdatingSitesFragment() is my fragment, I’m getting error to create ‘f’

    error: change type of ‘f’ to UpdatingSitesFragment() type. Please help soon.

    • Estevan

      In UpdatingSitesFragment, remove import android.app.Fragment, try import android.support.v4.app.Fragment

    • Jose Madrid

      You need to move the support jar file to your libs.

  • Nick M

    Could you possibly expand on this to include a list fragment in one of the tabs?

  • mhhra

    I have a problem, after creating the 3 tabs view and each code implemented in the xml files is seen on the GUI everything is fine. But once I run the project nothing appears under each tab.

  • Gilbert Sarip

    Thanks for the guide, but i have a button on on of the fragment, on button click it suppose to open a other “fragment”.

    Is it possible to replace the current fragment with a other one
    Thanks

    • Jose Madrid

      Yes you need to call the FragmentManager and do a Replace().

  • Fubar

    Great article — and all code does work. The only issue I had, being very new to android/java, was not understanding all the quick references that would come naturally with experience. Awesome job Ravi.

  • -=ILYA=-

    // MainActivity ->
    actionBar.setHomeButtonEnabled(false); // call requires API level 14
    // Manifest has this line: android:minSdkVersion=”11″

  • raamkum

    Has anybody tried this on API 9 and above…If so what are the changes.. I read the comments below there one who tried to use on Api 7 – I tried it but didn’t work. Can somebody help me out with this?

    • youming2007

      Yes. Run on Platforms from API 7 without any problems. Changes are: ActionBarActivity (instead of FragmentActivity), getSupportActionBar (instead of getActionBar), Theme.AppCompat in AndroidManifest and of course – include support library v7 into your project (see Android documentation for more details)

  • Ali Bagheri Shakib

    It’s so useful… Thanks a lot… πŸ™‚
    But what I should do if I don’t need the ActionBar?? I mean the tabs above, without “Entertainment” section as a bar. Just “Top Rated”, “Games” and “Movies”.

  • Thanks a lot…:)
    I have followed this tutorial. Now i want some modification. Suppose i have a button in GamesFragment. When i press this button i want to load another Fragment in Third Tab named DetailedFragment. How can i achieve that. Pls i need this badly. Help me

  • hemoali

    Please help me
    this is how it look on tablets
    http://i.imgur.com/Kn6k082.png

    how to make the tabs fill the whole area
    like this

    http://i.imgur.com/0fSw6rw.png

  • AbdoullahTJ

    Thank you !

  • Mark Runza

    how on earth do i change the tabs from text to drawable icons? can anyone help?

  • Jerry Salazar

    is possible put the tabs in bottom whit viewPager?

  • Luis Ruiz Figueroa

    how can I get the tabs fall below content?

    http://prntscr.com/3ro47k

  • Luis Ruiz Figueroa

    how can I get the tabs fall below content?

    http://i.imgur.com/B5MkXE3.png

    I currently above the content is below the action bar.

  • Toni Liem

    Very helpfull thanks for sharing!

  • Lokendra Yadav

    hello ravi sir I have used this example but first time getItem method of FragmentPagerAdapter is being called twice ,,how to ristrict it for once…plzzzz help me…

  • M Luthfan Mursyidan

    I follow your tutorial, but i got classnotdef exception. i read the comment below and follow the instruction to fix, but still no hope. error still appear. classnotdef appear because i deployed it to api 8.
    Still no have idea to integrate your code to support api < 11. Can you point me how to fix that?

    Thanks

  • dj-chen.com

    This is helpful, but if I have a navigation drawer in the app, the tab looks bad, because when we open drawer, it can not cover the tab. Do you have any idea how to solve this?

  • Mohammed

    Hi Ravi

    Thank for your help,in this tutorial and in your other tutorials.

    Please keep up the hard work.

    Kind Regards,
    Mohammed

  • Fjavier Amate

    thanks . For your help and your time.

  • Shivam

    Thanks Ravi, you had written a great tutorial. I exactly followed it.I want to transfer data from activity to fragments. I am not able to do this with bundle.(Bundle is always empty in Fragment class) Can you please help on this.

  • Arif YILMAZ

    Hi Ravi. I implement ViewPager from your tutorial and it works. I want to change fragment inside a tab. Actually I already changed it, but there is something strange. If I go to the next tab and come back there is no problem, but if I go to the third tab and come back, the old fragment come back. May I send my code to you?

  • Dr Duke

    Thanks a lot Ravi! really helpul and well written.

    I’d like to ask you which software did you use to draw the layout overview? (it’d be the Tabs-Illustration.jpg)

  • Ace Rbk

    Hello Ravi,I’v added an action bar up button,but when up is pressed which is supposed to go back to the last fragment,it rather loads the first homepage activity,i need to load the last fragment in tab rather.For instance,if i navigated from tab 2 to tab 3,when back is pressed,it should show tab3 fragment.

  • Hello @ravi8x:disqus thanks for your tutorial, I have a question, how to styling the tab style. I want to change default color so not using black and blue combination for the tab. I’ve been trying to add custom style on each fragment but the tab won’t change. thanks in advanced

  • Simon

    Hi nice Tutorial!
    Is it possible to update the TextView in the TabViews from MainActivity? I want to download data from server and then show this data in the textview in the tabviews. I want to download all data at once so I think it’s best to do this in MainActivity but i’m not able to update the textView.

  • Ali

    Thank you!
    I have been searching for a good and understandable tutorial but I couldn’t find it till I found your tutorial!

    It was perfect!
    Thank you so much

  • karimhasebou

    its not working for me. there is an error in the TabsPagerAdapter
    class. eclipse says The hierarchy of the type TabsPagerAdapter is inconsistent

  • akin

    hello Ravi,

    please his it possible i implement list view in each fragment? and how. please kindly assist

  • RB

    can i place this bar at the bottom of the page?

  • Ahmad

    Hi Ravi
    How can I always show tabs below the action bar? Like in Google Play App, the tabs show below the logo in every view on all devices.
    Thanks!

  • Alok

    It’s very good tutorial. You have mentioned TabHost has been deprecated. Have they mentioned this one in Developer Android. If it is can you pls pass out the link. I read that TabActivity has been deprecated.

  • drup

    hi..good tutorial..but when i run the program(even with your code also), I can see only action bar(Entertainment title) and rest is blank white page…no errors…where i went wrong…even i tried different emulation and changed graphical view..its same…pls suggest…..

  • hunterharada

    hi.. i’m make tab in one activity(TabActivity), and also i’m make sliding menu using fragment, but that tab in activity before should call in one of my fragment, how can i do that? anyone can help me?

  • Nico

    Hi. Does this solution work in Android 2.3.3? If not, what should be the alternative?

  • Anonymous

    Hola alguien podrΓ­a decirme como se aΓ±ade Admob en

    Android Tab Layout with Swipeable Views?

    Gracias por su ayuda πŸ™‚

  • Rohan

    hi How can i change background color of tabs bar

  • bosiang1

    Hi, how can I get the fragmentid or fragmenttag for this? I was working on this app, trying to update listView after asynctask done, but I’m not sure how to update a listview in my code. If you could help me it would be great. I open a question in stackOverflow: http://stackoverflow.com/questions/24873709/populate-listview-on-fragment-after-async-done-from-activity

  • NicolΓ‘s SchΓΌrmann Lindemann

    I’m interested in changing a textview after an async task done in the main activity. How can be done?

  • How can I prevent fragments from recreating. This approach calls onCreateView everytime i select a tab. I want to retain the previous state of the tab without recreating it.

    • Terrell

      I dont think so, each fragment is created once. You can see it when you put a Log.v to your Switch to each case option. Then you will see that getItem() is called onetime only for each fragment, then it calls only getCount(), but you can implement FragmentStatePagerAdapter instead of FragmentPagerAdapter if you need to save state of fragment.

    • I got it done using…
      setOffScreenPageLimit(int) method of ViewPager class

  • Hazim Sharif

    Hi, thanks for this tut, how do i change tabs text size please ?

  • Jonny 2 plates

    This is excellent…i’ve managed to implement a “Demo tutorial screen” – you know the ones that explain to users what your app does…i will be happy to share the project with anyone?

  • Pramoda

    thanks brother it’s good work…..

  • thank you so much,your tutorials always are goood and really help me,thanks man !!

  • Trent

    I have a question… I’m new to Android development so I’m not sure if this is a dumb question or not. When I try to run the project it gives me an error in TabsPagerAdaptor on the line that says “return new MoviesFragment();”. It says “java:incompatible types, required android.support.v4.app.Fragment, found: com.[project name].MoviesFragment”. I at first thought this meant I need to import android.support.v4.Fragment, but I already imported that so now I’m not sure what to do. If any of you lovely people know how to fix this that would be great. Thanks!

  • Juan

    Hi, im trying to show 4 tabs, and it makes it scrollable tabs but i want to show always the 4 tabs, what i am doing wrong? Thanks

  • Jorge Casariego

    Thank you Ravi!!

    It works perfect!

    • silentmind

      all of hiis codes works perfectly

  • Nightx

    Hi Ravi, the code works perfectly.. but how do i change tab text color using this method?? i want to change tab text color like into blue color..

  • The onCreateView() for the middle “Games” tab only gets called at start up.
    The first and last tabs work fine but when you select the “Games” tab the MainActivity.onTabSelected gets the correct position (item = 1) but it then calls the MoviesFragment.onCreateView() if you are coming from the “Top Rated” 1st tab. If coming from the “Movies” 3rd tab and select the middle “Games” tab it executes the TopRatedFragment.onCreateView() method.
    Anytime I select the “Games” tab, it does not execute any of the GamesFragment.java methods.
    I have modeled after this code for my 4 tab application and it is preventing the middle tabs from executing the initialization code needed for those tabs.

    Is there a bug in the underlying FragmentMangerImpl code?

    Note: The orange “Games” layout, however, is displayed correctly and the Games tab is selected.

  • Bhavesh Agarwal

    Can u please help me how to put the tabs at the bottom of the screen?

  • HO KA

    Hi Ravi.
    tnx, great tutorial.
    I have a question: how can I add some widget to each page view that can interact with other java class that do something different in each page view?
    I mean as you know we couldn’t swipe between activities so I tried to add activity to each page view. but I don’t know how.

  • very helpful article thank you Ravi :))

  • manta

    When I swipe between views the blue stripe moves only after a new view takes the whole screen.

    How can I make it move dynamically according to the users swipes? (like in the Google Play, if the screen shows something between two views the stripe will be between the two tabs)

    like this
    http://i.stack.imgur.com/8VFGw.jpg

  • Rajendra Achuri

    Hi Ravi;

    when i swipe the tabs on create is calling twice ,,can u pls suggest the solution

  • Mina Gabriel

    Cool what is the name of the tool you used to create the layout overview mock-up?

  • Aryan

    Excellent tutorial but a small suggestion. The line actionBar.setHomeButtonEnabled(false); actually does no work other than increasing min API. The line requires API 14 while without this line, the code works fine on API 11 too.

  • Bono de Visser

    In the TabsPagerAdapter make sure you import the following files:
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;

    I let Android Studio import mine by default, but it imported different ones. When I was trying to pass getSupportFragmentManager() to the TabsPagerAdapter constructor in the MainActivity it kept complaining that I was using the wrong version. Importing the correct files will help get rid of the problem.

  • Pranav Lathigara

    How to Change Layout or Background of Tab..?

  • A S

    Hi Ravi, Your tutorials always give clear insight on things. Can you tell me how to make the top line bar (Action Bar) not visible to the users in THIS particular example?? I had made an app sometime back with similar code but the top line did create an issue with me… any help?

  • Aryan Gaikwad

    @Ravi, there is a small suggestion. The tabs get focused when I slide but when I click on any tab, no action is performed. Plz update the code.

  • Vladimir Makarov

    this method actually sucks , not the tutorial mate, no offence,you and the tutorial are rock solid, the method sucks because the action bar tabs cannot be customized easily to change its background or do other things with it, even if you find the styles for action bar and change it, there are issues with pre honeycomb and post honeycomb devices, what i rather would suggest is to have a ViewPager+TabHost with custom indicators and tab layouts that can be customized easily compared to this… πŸ˜€ but hey good one

  • Dinesh Babu

    good Ravi

  • Er Krishna Gadgul

    Thank You Ravi …………………….. It will helped me lot

  • Akshata

    Thanks this did help me a lot..but i am unable to change the color of my tabs text even after lot of trial and error, hence needed some guidance regarding the same.

    • Vishnu

      πŸ™‚

  • Vishnu Mohan

    Thanks dude for this awesome and simple tut. You saved my day

  • shaki

    please help me i want to add a listview with images in tab
    what to do ??

  • anamika

    nice was very helpful. may god bless you and people like you

  • Ali

    Hi, please tell me how to instantiate buttons or use findviewbyid in MoviesFragment.java or other activities..

  • Syarif Ibnu Miftahudin Al-Dami

    Can i hide or remove actionBar but still showing the tabs? I hide the actionBar but all tabs are hidden too.

  • Mark Valenzona

    Thanks for this. I have a problem though in Fragments. How can I put images in a ListView in a Fragment?

  • Prashaant Maheshwari

    Hi Ravi ,
    how can i use this tabs in fragment means in my main activity i am replacing multiple fragments in a frame layout using fragment transaction so how can use this tabs inside fragment.

  • Richard

    I have tabbed navigation for the main catagories of my app, but the activities that are called from those do not show the tabs.

  • Tanish

    Thanks for the clear and concise tutorial. I added two methods to each of the fragments: onAttach and onResume. However i dont see the results that I am expecting. When the first tab(TopRatedFragment) gets selected..i see logs as
    TopRatedFragment::onAttach…
    TopRatedFragment::onResume
    GamesFragment::onAttach…
    GamesFragment::onResume
    Then when I select Games Tab, I see
    MoviesFragment::onAttach…
    MoviesFragment::onResume
    I never see GamesFragment onResume thereafter no matter which Tab i select ..

    Could you please throw some light here?

  • Alan Marcel

    Tamada, great tutorial! Thank you!
    I just would like to say you should emphasize the AndroidManifest.xml. What do you think show this file at the end of the article?
    Best regards!

  • k

    Hi,
    i implement async call in two fragment,i am on tab 3 when i move to tab 2 it call tab1,why this behavior?where i implement async call which only call one time not wach time tab change

    • k

      not “each” time tab change

  • subbramanian

    Hi,
    Awesome article.. Thanks a lot…
    Could you pls give some hints on how to add images instead of text in the tab. As tabhost is deprecated, I couldnt find any proper details anywhere for adding images.

  • Tianlei Hou

    This is a really awesome source, thanks for the posting

  • bhushan

    how can i add now button on any of fragment

  • Alireza saemi

    hello android hive … y favorite tutorial site … my development home

    i asked it once and u say it can be .. can we have scrollable tabs along side with navigation drawer ? i can not implement two of them because they are both fragments … this is so usefull for every one . lot of big app using this .. can u put us tutorial please ?

    ireally love your site and effort ,,, your tutorial is awesome and runs even on studio … please put it in way that gradle can run it … android studio .

    will be glad if u answer me can we have it or no ? tell me truth i will be grateful if you even say no

    • Hi Alireza, I haven’t tried tabs with navigation drawer. May be you can try this once
      http://www.paulusworld.com/technical/android-navigationdrawer-sliding-tabs

      • Alireza saemi

        i really going to love india ppl , they are really develop passionate . thank u so much . other question is can we use this swipable tab views in android gingerbread and above ?

        • Alireza saemi

          as always i ran this project with adt and eclipse and every thing went well :(((((
          .. i really sometimes get tired of this gradle thing and what google
          put us in disaster with migrate to gradle .. there are lot of conflict
          .. i don’t know how to fix it to work with gradle . πŸ™

      • Alireza saemi

        ………………………….

      • Alireza saemi

        i tried that method but give me so strange error … im sry and just asking , sure u an say no to me , i have no time .. i respect you and your time .

        i explained error ofcource there but my cm not moderated .. here is strange error did u saw this error before ? can u test that zip project and see it runs for you . this is my wierd error , i search alot on stack overflow but couldn’t figure out :

        Error:Execution failed for task ‘:app:dexDebug’.
        > com.android.ide.common.internal.LoggedErrorException: Failed to run command:
        E:multimediaAndroid Studio Versionssdkbuild-tools19.1.0dx.bat –dex –output C:UsersdeveloperAndroidStudioProjectsDrawerNavigationTabsImportedappbuildintermediatesdexdebug C:UsersdeveloperAndroidStudioProjectsDrawerNavigationTabsImportedappbuildintermediatesclassesdebug C:UsersdeveloperAndroidStudioProjectsDrawerNavigationTabsImportedappbuildintermediatesdependency-cachedebug C:UsersdeveloperAndroidStudioProjectsDrawerNavigationTabsImportedappbuildintermediatespre-dexeddebugandroid-support-v13-e845856e278db22f834cd98a2182a0397826950c.jar C:UsersdeveloperAndroidStudioProjectsDrawerNavigationTabsImportedappbuildintermediatespre-dexeddebugsupport-v4-19.1.0-f98d3d7a948c5cb520a96c7b1bb012e50ed59ece.jar
        Error Code:
        2
        Output:
        UNEXPECTED TOP-LEVEL EXCEPTION:
        com.android.dex.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
        at com.android.dx.command.dexer.Main.run(Main.java:230)
        at com.android.dx.command.dexer.Main.main(Main.java:199)
        at com.android.dx.command.Main.main(Main.java:103)

        i know u are busy bro , just to see if u see such an error

  • myhead

    Hello ! Thank you so much for your guide, it’s clear and it works perfectly. I’d have just one question : I created a new ‘fragmented’ activity and I open it from the main activiy with an Intent. Is there a way to open a specific fragmentation of the activty ? For instance: I have 3 buttons in the main activity and each of them has to open a specific fragmentation. (Button1 -> Tab 1 ; Button2 -> Tab2 ..etc.. ).
    Thanks in advance for any reply

    • myhead

      I meant ‘fragment’ of the activity. My bad.

    • myhead

      I solved it. I’ll explain for the posterity πŸ™‚
      I started a new activity in a onClick event adding some extras.

      Intent i = new Intent(this, TabsActivity.class);
      i.putExtra(“variable_name”, value);
      startActivity(i);

      Then in the TabsActivity I retrieved the values in this way:

      int variable = 0;
      Bundle extras = getIntent().getExtras();
      if (extras != null) {
      variable = extras.getInt(“variable_name”);
      }

      And finally I passed the value to the TabsPagerAdapter by using setSelectedNavigationItem in this way:

      actionBar.setSelectedNavigationItem(variable);

      Hope it’ll help someone with same ‘problem’. πŸ™‚
      See ya

  • Alireza saemi

    any wau thank u so much man. that tutorial u give me working on eclipse . do u think i should program on eclipse and how about mke xml file on studio πŸ˜€ . until it comming to stable version

  • Mardoqueu

    I got a problem, I’m using a in the tab “Move”, a splash screen, but when I click in “Game”, the tab Move is aclivity and a new activity open as, what much I to do to the splash screen works just when I click in Game?

  • dhnjy 18

    Hi,,Great tutorial working fine……But how can i remove tab divider between two Tabs?

  • Sascha

    Great Tutorial, thank you so much! Works perfect!

  • seetha

    Ravi,

    android.app.ActionBar.TabListener – This interface was deprecated in API level 21.
    Action bar navigation modes are deprecated and not supported by inline toolbar action bars. Consider using other common navigation patterns instead.

    But browsing at common navigation patterns don’t give any indication of how the TabSelector interface methods such as TabSelected, TabUnselected can be implemented.

    Now on API 21, pls suggest what changes I should make in the code above to work. Thanks.

  • baskar

    can anyone tell me how to customize the tab indicator(The blue strip that shows the current tab). Thanks in advance

  • Hyunji

    ThankYou very Much!!!!!!!
    i success!!!

  • Ankit Sharma

    Hi Ravi,

    Can we disable actionbar where entertainment text is listed?

    • amir

      getSupportActionBar().setDisplayShowHomeEnabled(false);
      getSupportActionBar().setDisplayShowTitleEnabled(false);

  • Ω…Ψ­Ω…Ψ― عرفان

    what shld i do if i want only two tabs?
    i changed the String[] tabs with two strings,
    and i removed case 2 from switch in TabsPagerAdapter class,
    now if i swipe the application is closing by saying “Unfortunately app has stopped working”
    need help

  • Rohit Bandil

    when i am going tab-1 to tab-3 tab is scrolling and again listView is loading in fragment. i am using ListView in fragment and attached in tab-3 .so plz give me clarity i dont want to load agian my listView in fragment that attach in tab-3.

  • Biswajit Jena

    Hi, Thanks it’s a great tutorial. Can we set the actionbar tabs on bottom of the sceen?

  • Omar Ayed

    how can to alignment the tabs to right not a left , this mean to start in the right

  • Manideep

    My Requirement:

    As we have 3 Tabs ,I want to validate the fields present in Tab1 and then only user should be allowed to navigate to tab2 ,and also send the data from Tab1 to tab2.

    Same in case of tab2 to tab3.

    I tried doing this in Main Activity where we implement TabListener interface but not able to achieve this.

    Please provide the code snippet which can help me.

  • Manuel SΓ‘nchez

    Hello I want to know what I have to do to select an starting fragment, in my app I want to in a determinate day load a position, for example, monday is 0, tuesday is 1, wednesday is 2, im not asking how to know which day is which position, just how to send that information to the fragments, tried viewpager.setcurrentitem, but no luck, thanks in advance

  • everest

    How to add listview to the tab???
    plz help

    • public class YourEvents extends ListFragment {

      private Button batchRequestButton;

      private TextView textViewResults;

      @Override

      public void onActivityCreated(Bundle savedInstanceState) {

      super.onActivityCreated(savedInstanceState);

      // 1. pass context and data to the custom adapter

      Log.w(“myApp1”, String.valueOf(Wymiana.wydarzenia.size()));

      MyAdapter adapter = new MyAdapter(getActivity(), neededDATA);

      //2. setListAdapter

      setListAdapter(adapter);

      }

      package lukaszStore.SCounter;

      import java.util.ArrayList;

      import java.util.HashMap;

      import java.util.Map;

      import lukaszStore.SCounter.adapter.Item;

      import android.content.Context;

      import android.graphics.Color;

      import android.view.LayoutInflater;

      import android.view.View;

      import android.view.ViewGroup;

      import android.widget.ArrayAdapter;

      import android.widget.ImageView;

      import android.widget.TextView;

      public class MyAdapter extends ArrayAdapter<HashMap<String, Pair>> {

      private final Context context;

      private final ArrayList<HashMap<String, Pair>> itemsArrayList;

      public MyAdapter(Context context, ArrayList<HashMap<String, Pair>> itemsArrayList) {

      super(context, R.layout.row, itemsArrayList);

      this.context = context;

      this.itemsArrayList = itemsArrayList;

      }

      @Override

      public View getView(int position, View convertView, ViewGroup parent) {

      // 1. Create inflater

      LayoutInflater inflater = (LayoutInflater) context

      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      // 2. Get rowView from inflater

      View rowView = inflater.inflate(R.layout.row, parent, false);

      // 3. Get the two text view from the rowView

      ImageView image = (ImageView) rowView.findViewById(R.id.icon);

      TextView labelView = (TextView) rowView.findViewById(R.id.label);

      TextView valueView = (TextView) rowView.findViewById(R.id.value);

      HashMap<String, Pair> _temp = itemsArrayList.get(position);

      String _tempKey= _temp.keySet().toArray()[0].toString();

      Pair _tempValues = (Pair) _temp.get(_tempKey);

      String _tempValuesLeft = _tempValues.getLeft();

      String _tempValuesRight = _tempValues.getRight();

      // 4. Set the text for textView

      if(_tempValuesRight.equals(“attending”))

      {

      image.setImageResource(R.drawable.attending);

      rowView.setBackgroundColor(Color.rgb(95, 207, 96));

      }

      else if(_tempValuesRight.equals(“created”))

      {

      image.setImageResource(R.drawable.created);

      rowView.setBackgroundColor(Color.rgb(165, 255, 255));

      }

      else if(_tempValuesRight.equals(“maybe”))

      {

      image.setImageResource(R.drawable.maybe);

      rowView.setBackgroundColor(Color.rgb(255, 255, 114));

      }

      else if(_tempValuesRight.equals(“not_replied”))

      {

      image.setImageResource(R.drawable.not_replied);

      rowView.setBackgroundColor(Color.rgb(255, 185, 114));

      }

      else if(_tempValuesRight.equals(“declined”))

      {

      image.setImageResource(R.drawable.declined);

      rowView.setBackgroundColor(Color.rgb(255, 112, 63));

      }

      if(_tempValuesLeft.length()>48)

      {

      labelView.setText(_tempValuesLeft.substring(0, 45)+”…”);

      }

      else

      {

      labelView.setText(_tempValuesLeft);

      }

      valueView.setText(_tempKey);

      // 5. retrn rowView

      return rowView;

      }

      }

  • Sanjh

    So far m able to send the data from fragment A(Top Rated) to fragment B(Games)
    But Unable to setText in fragment B,

    Fragment A
    FragmentB fragment = new FragmentB ();
    Bundle args = new Bundle();
    args.putString(“TotalCons”, totalCons);
    args.putString(“TotalPieces”, totalPieces);
    fragment.setArguments(args);
    System.out.println(args);
    getFragmentManager().beginTransaction().add(R.id.pager, fragment).commit();

    Fragment B:

    in OnCreateView()

    Bundle args = this.getArguments();
    if(args!= null){
    String TotalConsAdpater = getArguments().getString(“TotalCons”);
    Log.d(LOG_TAG,”Consignment Fragment TotalCons:”+TotalConsAdpater);
    TotalCons.setText(TotalConsAdpater); // ###unable to set This text its just nada

    String TotalPcsAdpater = getArguments().getString(“TotalPieces”);
    Log.d(LOG_TAG, “Consignment Fragment TotalPcs:” + TotalPcsAdpater);
    TotalPieces.setText(TotalPcsAdpater);// ###unable to set This text

    }else{
    System.out.println(“Empty Bundle in ConFragment:”);
    }

  • bhavna

    why are we using fragments here?

  • Sercan

    Hello , this is not working on android 2.3.6 version please help me. How to work in low version?

  • Asun VR

    Thanks a lot!.
    This tutorial is really great.
    I would like to comment a problem I had due to the new android themes versions. This project crashes if we use “Theme.AppCompat” . The method getActionBar() in MainActivity was returning null and the app crashes, but I could resolved it changing the theme style to Theme.Holo.Light. I hope this info help somebody. Again, I would like to thank to Ravi Tamada this great site.

    • Yukari Yuu

      Hi Asun VR…
      I try this tutorial.. and like u say, it’s always crashes. I use Theme.AppCompat too. Can you tell me, how to apply Theme.Holo.Light?
      because i cant change it in my style.xml

      • Muhammad Khalid Rahman

        i just deleted android:theme=”@style/Theme.AppCompat”

        from manifest file & it works πŸ™‚

  • Amarildo Aliaj

    Hi, fantastic tutorial, but the download code button don’t work

  • John David

    great tutorial..
    can u tell me how to change the tab names (games) into images?

    • ezaaa

      view the code and you’ll find it.zz

    • Behnam Heydari

      you must change this line
      private String[] tabs = { “Top Rated”, “Games”, “Movies” }; to
      private String[] tabs = { “Top Rated”, “images”, “Movies” };

  • Behnam Heydari

    Hi Ravi ! thank you for great tutorials

    can i just hide “action bar tab” not action bar? i want swap able fragment like three page you have here but just not showing which one is selected.
    i change setNavigationMode to standard and it crash if i swap πŸ™‚ what can i do ?

    thanks

  • ezaa

    can u give me a specs of device on eclipse that will work on this. Thanks

  • Adarsha

    Suppose I have to show the Movies fragment at the start of the activity, how can I declare it in the code?

  • Munim

    Thanks for the great tutorial Ravi. Is there any way to do this using fragment instead of fragmentActivity? Thanks.

    • Edmhar

      Are you compiling it with Navigation Drawer right?

      • Munim

        Yes! πŸ™‚ With navigation drawer. If you can help me out with this, that will be great. Thanks.

        • Edmhar

          I’m also doing that and I check the net they say it can’t.

          • Munim

            I dont think its impossible, but we have to change something. Ravi used fragmentactivity that is causing problem with navigation drawer. So one way to make it work is change to fragment or change how fragments load from navigation drawer.

          • …/2013/11/android-sliding-menu-using-navigation-drawer/
            check out this tutorial from Ravi

  • John David

    how to change the tab indicator colour?

  • Thank you sooooooo much!

  • Emircan

    Its so good but , these classes android.app.ActionBar.Tab; and tablistener are deprecated.
    What we should do now ? πŸ™‚

  • kuku

    Nice tutorial …:)
    but i want add data under these tabs ..like Google play store …
    how i can do ..:(
    Any One tell me please

  • jithea23

    Great tutorial.. but i have a problem, is it possible to add FragmentActivity in the TabsPagerAdapter?

  • Jaideep Rawat

    hi great 1..
    how can we change the taskbar color??

  • Jose Pablo MB

    Hi! Great tutorial dude!
    Just one question: when i’m making the pager adapter, I get an error if I return the fragment.. The fragment class is the child of Fragment as in your example but it’s not letting me return it.
    Do you know why is that?
    Thanks

    • Third

      Change this import from your Fragment Class:

      import android.app.Fragment;

      to this:

      import android.support.v4.app.Fragment;

  • genericid

    In one of the fragments:

    View rootView = inflater.inflate(R.layout.fragment_games, container, false);
    return rootView;

    If I am extending the Fragment class, why do we return a View?

  • Amir Bhujel

    Thank you for the tutorial.
    Worked great.

    But I am using a Navigation Drawer too in the application.
    The problem I am facing is that the Navigation Drawer should overlap the titles of the Tabs which I am unable to do as they are set in the ActionBar.

    Can anyone help me to get rid of this issue??
    I guess it would be done by using the PageTitleStrip. But how to implement it??

  • Action bar navigation modes are now deprecated in Android L ,all methods related to navigation modes in the ActionBar class (such as setNavigationMode(), addTab(), selectTab(), &c). are now deprecated.Now a Toolbar is a generalization of action bars for use within application layouts.

  • Pablo

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    These methods doesn’t work in API Level 10, as you show when you create the project.

  • Crivi

    Very good tutorial, but unfortunately as Pablo sad all the main methods are deprecated.
    Can you please try to make a tutorial with an alternative solution.
    Congrats for your tutorial, they are the best!

  • maximus

    cant resolve symbol ‘FragementActivity’..Cant we use just Activity??

  • Tiregan

    Hello,
    Thanks for this nice tutarial πŸ™‚
    I am trying add something (for excample Plain text) above thses tabs and I can’t… I tried by margin but it work only for tabs content, not actionBar.
    Could You help with this?

    Thanks,
    T.

  • Hello,
    Is this possible to hide Title Bar without removing Action Bar?
    Thanks πŸ™‚

  • whueeeeey

    Hello there, thanks for amazing tutorial!

    Is there any other way how to donload the code? Link does not work for me.

    “ReadResponse() failed: The server did not return a response for this request. Server returned 0 bytes.”

  • Sanjay Mangroliya

    Hi ravi i m use your tutorial i have one question how to go TopRatedFragment To GamesFragment
    when button on click

    Fragment gameFragment = new GamesFragment ();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.pager, gameFragment );
    transaction.remove(new RatesFragment());transaction.addToBackStack(null);
    transaction.commit();

    i m use this code but not perfect work

  • Thien Nguyen

    I’m using Android Studio but my getActionBar() returns null. How do I fix this?

  • Great Tutorial.But it show error.Cannot instantiate TabsPagerAdapter. what to do
    ??

    • Solved It..Can I Add into Navigation Drawer? What changes Occur in mainActivity.java.

  • Ismaele Bottelli

    Hi! Great tutorial, but now the method actionBar.setNavigationMode (and other..) are deprecated. Could you explain me how to solve the problem?

  • pushpa

    1. actionBar.setSelectedNavigationItem(position);
    2 .actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    says it may return nullpointerexception. how to solve these errors?

  • kiran guled

    Hi πŸ™‚ I have used above code and added list fragment in three tabs,only at the time of creation all three tabs is getting loaded,but i need to reload list on click of tab.How to do that?? can anyone help me,,

  • Usman

    How do I reference to the objects in xml layouts?

  • Santosh Bhandary

    how is it possibe to control auto slide inside ViewPager from a button event handling ?
    I tried it using Handler with Runnable thread but all messed up .need some help guys