Vous êtes sur la page 1sur 19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Android Tab Layout with Swipeable Views


463 Comments . By Ravi Tamada . on October 6, 2013

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

London
Accommodations
UniqueRentalsinLondon.
Bookaccommodationsfrom
$49/night.

fragments and viewpager. Also you can swipe between


tab view as it is the functionality of viewpager which is
not possible when using TabHost.
AdvertiseHere

DOWNLOAD CODE

VIDEO DEMO

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

1/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Android Tab Layout with Swipeable Views

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

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

2/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Creating new Project


Even though you are not familiar with ViewPager or Fragments, dont worry. You will get an idea about
what those are and how to use them once you are done through this article. So lets 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.
http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

3/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

2. As we are going to use Fragments, extend your main activity from Fr agmen t Acti vit y . Also
implement this class from Act ion Ba r. Ta bL is ten er as we are adding Tabs too.

publicclassMainActivityextendsFragmentActivityimplements
ActionBar.TabListener{
3. Open main activity layout file and add Vi ewP ag er element. (My layout file for main activity is
activity_main.xml)

ACTIVITY_MAIN.XML
http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

4/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

<android.support.v4.view.ViewPagerxmlns:android="http://schemas.android.com/apk/res/and
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 Fr agmen t Pa gerA da p ter 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.

TABSPAGERADAPTER.JAVA
packageinfo.androidhive.tabsswipe.adapter;

importinfo.androidhive.tabsswipe.GamesFragment;
importinfo.androidhive.tabsswipe.MoviesFragment;
importinfo.androidhive.tabsswipe.TopRatedFragment;
importandroid.support.v4.app.Fragment;
importandroid.support.v4.app.FragmentManager;
importandroid.support.v4.app.FragmentPagerAdapter;

publicclassTabsPagerAdapterextendsFragmentPagerAdapter{

publicTabsPagerAdapter(FragmentManagerfm){
super(fm);
}

@Override
publicFragmentgetItem(intindex){

switch(index){
case0:
//TopRatedfragmentactivity
returnnewTopRatedFragment();
case1:
//Gamesfragmentactivity
returnnewGamesFragment();
case2:
//Moviesfragmentactivity
returnnewMoviesFragment();
}

returnnull;
}

@Override
publicintgetCount(){
//getitemcountequaltonumberoftabs
http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

5/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

return3;
}

Adding Tabs to Action Bar


6. In order to display tabs we dont 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.

MAINACTIVITY.JAVA
publicclassMainActivityextendsFragmentActivityimplements
ActionBar.TabListener{

privateViewPagerviewPager;
privateTabsPagerAdaptermAdapter;
privateActionBaractionBar;
//Tabtitles
privateString[]tabs={"TopRated","Games","Movies"};

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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

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

//AddingTabs
for(Stringtab_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.
http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

6/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

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.

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

7/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

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.

FRAGMENT_TOP_RATED.XML

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a">

<TextViewandroid:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DesignTopRatedScreen"
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.

TOPRATEDFRAGMENT.JAVA
packageinfo.androidhive.tabsswipe;

importinfo.androidhive.tabsswipe.R;
importandroid.os.Bundle;
importandroid.support.v4.app.Fragment;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;

publicclassTopRatedFragmentextendsFragment{

@Override
publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
BundlesavedInstanceState){

ViewrootView=inflater.inflate(R.layout.fragment_top_rated,container,

returnrootView;
}
}

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

8/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

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

FRAGMENT_GAMES.XML

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400">

<TextViewandroid:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DesignGamesScreen"
android:textSize="20dp"
android:layout_centerInParent="true"/>

</RelativeLayout>
10. Create a new class named GamesFragment.java with following code.

packageinfo.androidhive.tabsswipe;

importinfo.androidhive.tabsswipe.R;
importandroid.os.Bundle;
importandroid.support.v4.app.Fragment;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;

publicclassGamesFragmentextendsFragment{

@Override
publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
BundlesavedInstanceState){

ViewrootView=inflater.inflate(R.layout.fragment_games,container,false

returnrootView;
}
}

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

9/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

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

FRAGMENT_MOVIES.XML

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#17df0d">

<TextViewandroid:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DesignMoviesScreen"
android:textSize="20dp"
android:layout_centerInParent="true"/>

</RelativeLayout>
12. Also create activity class for this view named MoviesFragment.java

MOVIESFRAGMENT.JAVA
packageinfo.androidhive.tabsswipe;

importinfo.androidhive.tabsswipe.R;
importandroid.os.Bundle;
importandroid.support.v4.app.Fragment;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;

publicclassMoviesFragmentextendsFragment{

@Override
publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
BundlesavedInstanceState){

ViewrootView=inflater.inflate(R.layout.fragment_movies,container,false

returnrootView;
}

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

10/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

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

And this is how it looks in landscape mode

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

11/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Tab Change Listener


If you run the project you can see the swiping views working, but if you select a tab, view wont change
automatically. This is because ViewPager didnt 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.

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

12/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

@Override
publicvoidonTabReselected(Tabtab,FragmentTransactionft){
}

@Override
publicvoidonTabSelected(Tabtab,FragmentTransactionft){
//ontabselected
//showrespectedfragmentview
viewPager.setCurrentItem(tab.getPosition());
}

@Override
publicvoidonTabUnselected(Tabtab,FragmentTransactionft){
}

View Change Listener


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

/**
*onswipingtheviewpagermakerespectivetabselected
**/
viewPager.setOnPageChangeListener(newViewPager.OnPageChangeListener(){

@Override
publicvoidonPageSelected(intposition){
//onchangingthepage
//makerespectedtabselected
actionBar.setSelectedNavigationItem(position);
}

@Override
publicvoidonPageScrolled(intarg0,floatarg1,intarg2){
}

@Override
publicvoidonPageScrollStateChanged(intarg0){
}
});
After adding these two listeners, if you run the project you can see everything working good.

Complete Code
http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

13/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Below is the complete code for MainActivity.java class

MAINACTIVITY.JAVA
packageinfo.androidhive.tabsswipe;

importinfo.androidhive.tabsswipe.adapter.TabsPagerAdapter;
importinfo.androidhive.tabsswipe.R;
importandroid.app.ActionBar;
importandroid.app.ActionBar.Tab;
importandroid.app.FragmentTransaction;
importandroid.os.Bundle;
importandroid.support.v4.app.FragmentActivity;
importandroid.support.v4.view.ViewPager;
importandroid.view.Menu;

publicclassMainActivityextendsFragmentActivityimplements
ActionBar.TabListener{

privateViewPagerviewPager;
privateTabsPagerAdaptermAdapter;
privateActionBaractionBar;
//Tabtitles
privateString[]tabs={"TopRated","Games","Movies"};

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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

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

//AddingTabs
for(Stringtab_name:tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}

/**
*onswipingtheviewpagermakerespectivetabselected
**/
viewPager.setOnPageChangeListener(newViewPager.OnPageChangeListener(){

@Override
publicvoidonPageSelected(intposition){
//onchangingthepage
//makerespectedtabselected
actionBar.setSelectedNavigationItem(position);
}

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

14/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

@Override
publicvoidonPageScrolled(intarg0,floatarg1,intarg2){
}

@Override
publicvoidonPageScrollStateChanged(intarg0){
}
});
}

@Override
publicvoidonTabReselected(Tabtab,FragmentTransactionft){
}

@Override
publicvoidonTabSelected(Tabtab,FragmentTransactionft){
//ontabselected
//showrespectedfragmentview
viewPager.setCurrentItem(tab.getPosition());
}

@Override
publicvoidonTabUnselected(Tabtab,FragmentTransactionft){
}

Share this article on


559

37

Like

Tweet

168

You May Also Like

Android Working with

Android Fullscreen

Android Sliding Menu

Android Combining Tab

Action Bar

Image Slider with Swipe

using Navigation Drawer Layout and List View

and Pinch Zoom


Gestures

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

15/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Ravi Tamada
Hyderabad, INDIA

Subscribe to get latest updates to your inbox.


-- I dont spam!

Enter your email here

SUBSCRIBE

Advertise

AdvertiseHere

Bluetooth Starter Kit


Jump start your bluetooth data
app with a flexible PIC32 starter
kit
www.microchip.com/pic3...

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

16/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

AndroidHive
30,968likes

LikePage

ContactUs

Bethefirstofyourfriendstolikethis

Tag Cloud
Action Bar

Adapter

Apps

Async

Chat

Dashboard

File Upload

Location

PHP

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

GPS

GCM

Grid

Grid View

Locale

Material Design

Navigation Drawer
Pinch

GDK

json

List View

Maps

facebook

Google Glass

Intermediate

Libstreaming

API

Camera

Database

Google

Google Plus

MySQL

Beginner

Fragments

Gestures

HTTP

Animation

PayPal

Progress Bar

17/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

Push Notifications
RecyclerView
SMS

REST

Sockets

sponsored
Twitter

sessions

Speech Input

SQLite

UI

View Pager

Quick Tips

Swipe

Video
Volley

Slim
Spinner

Tab View

Video Streaming
Wearable

xml

YouTube

Ravi Tamada
google.com/+RaviTamada
Theo di
13.231 ngi theo di

Most Popular
1

Android SQLite Database Tutorial - 1,142,024


views

How to connect Android with PHP, MySQL 1,074,690 views

Android JSON Parsing Tutorial - 964,849


views

Android Push Notifications using Google


Cloud Messaging (GCM), PHP and MySQL -

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

18/19

13/8/2015

AndroidTabLayoutwithSwipeableViews

883,440 views
5

Android Custom ListView with Image and


Text - 838,131 views

Android

Sliding

Menu

using

Navigation

Drawer - 755,063 views


7

Android Login and Registration with PHP,


MySQL and SQLite - 702,618 views

Android GPS, Location Manager Tutorial 533,836 views

Android Tab Layout Tutorial - 516,233 views

10 Android Tab Layout with Swipeable Views 496,808 views

LondonAccommodations
UniqueRentalsinLondon.Bookaccommodationsfrom$49/night.

Copyright AndroidHive

http://www.androidhive.info/2013/10/androidtablayoutwithswipeableviews1/

Advertise . Privacy Policy . Terms & Conditions

19/19

Vous aimerez peut-être aussi