Android Actionbar Navigating with Swipeable Tabs

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

Basically we are using ViewPager as main layout and for individual pager views we use Fragments. The tabs are part of Action Bar.
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.

http://androidgreeve.blogspot.in/p/blog-page.html
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.

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. (File name:  layout file for main activity is activity_main.xml)
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 com.androidgreeve.tabs_swipeviews.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 com.androidgreeve.tabs_swipeviews.adapter;

import com.androidgreeve.tabs_swipeviews.NewsFragment;
import com.androidgreeve.tabs_swipeviews.productivefragment;
import com.androidgreeve.tabs_swipeviews.socialfragment;
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 NewsFragment();
        case 1:
            // Games fragment activity
            return new productivefragment();
        case 2:
            // Movies fragment activity
            return new socialfragment();
        }

        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 News, social,Productive 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
 
public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Social", "Organizer", "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.

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 added icons of app with some background color.

First Tab View

7. The first tab I added is News app. Create a new layout file under src --> res folder named fragment_Newsapp.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">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="97dp"
        android:layout_marginTop="37dp"
        android:src="@drawable/apple2" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/imageView1"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="18dp"
        android:src="@drawable/blogger" />

8. Also create respected Fragment activity class for this view. Create a new class named NewsFragment.java under your main package.
package com.androidgreeve.tabs_swipeviews;
    import com.androidgreeve.tabs_swipeviews.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 NewsFragment extends Fragment {

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

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


Second Tab View

The second tab in the list is Productive. 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_Productive.xml

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView1"
        android:layout_marginRight="28dp"
        android:layout_toLeftOf="@+id/imageView1"
        android:src="@drawable/calendar" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView2"
        android:layout_marginRight="30dp"
        android:layout_toLeftOf="@+id/imageView2"
        android:src="@drawable/camera" />


10. Create a new class named ProductiveFragment.java with following code.
package com.androidgreeve.tabs_swipeviews;
    import com.androidgreeve.tabs_swipeviews.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 productivefragment extends Fragment {

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

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

Third Tab View

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

11. Create a layout file called fragment_Social.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="#000">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/imageView4"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="62dp"
        android:src="@drawable/googleplus" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView3"
        android:layout_alignLeft="@+id/imageView1"
        android:layout_marginBottom="34dp"
        android:src="@drawable/linkedin" />


Also create activity class for this view named socialfragment.java
package com.androidgreeve.tabs_swipeviews;

    import com.androidgreeve.tabs_swipeviews.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 socialfragment extends Fragment {

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

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

Run the project and check whether the views for tabs are added or not.
WBY8QT8AT4ZZ
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.
package com.androidgreeve.tabs_swipeviews;

import com.androidgreeve.tabs_swipeviews.adapter.TabsPagerAdapter;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Social", "Organizer", "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) {
    }

}


14 comments

very nicely written great!

Reply

hey nice post can u write on list view

Reply

very nice written brilliant!

Reply

nice what about your app?//

Reply

is it possible if i add a button one of the view & run onlick to replace the view with a other view

Reply

Thanks!!!!!!! This really helped me as i couldn't see the selected tab when swiping! Thanks!!!

Reply

Thanks a lot for the tutorial
I have a question , what should if I want the swipe views be horizontally?
I mean I changed the app orientation in manifest and I made it "landscape" , and now I want it to swipe horizontally , not vertically! I mean the view changes when i move up and down , not left and right!
Is there any way to do it?

Reply

Thanks a lot for the tutorial

I have a question , what should if I want the swipe views be vertically?

I mean I changed the app orientation in manifest and I made it "landscape" , and now I want it to swipe vertically , not horizontally! I mean the view changes when i move up and down , not left and right!

Is there any way to do it?

Reply

Subscribed but not able to download source code

Reply

Here is the question, how can i make my tabs size smaller instead of spreading them whole action bar? I mean i want actionbar like that, but i will put a options menu icon near the tabs

Reply

Thnx a lot...can you provide tutorial on adding items to list view dynamically on reaching the end of scroll...

Reply

Subscribed but not able to download source code

Reply

Post a Comment