Android ActionBar Tabs with swipeable views using ActionBarSherlock

In the previous post we looked about the ActionBarSherlock basic .In these Post we look to develop the Swipe tab Example Using ActionBarsherlock this would give a complete idea of  difference.


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.Add the ActionBarSherlock  to your project

3.As we are going to use Fragments, extend your main activity from SherlockFragmentActivity
Another requirement in order to use Sherlock library is that your activity should extend from SherlockFragmentActivity. Also implement this class from ActionBar.TabListener as we are adding Tabs too.

public class MainActivity extends SherlockFragmentActivity implements

        ActionBar.TabListener {


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


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

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

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

    private ActionBar actionBar;
    private ViewPager viewPager;

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

        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setOnPageChangeListener(onPageChangeListener);
        viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
        addActionBarTabs();
    }

    private ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            actionBar.setSelectedNavigationItem(position);
        }
    };

    private void addActionBarTabs() {
        actionBar = getSupportActionBar();
        String[] tabs = { "Social", "News", "Productive" };
        for (String tabTitle : tabs) {
            ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
                    .setTabListener(tabListener);
            actionBar.addTab(tab);
        }
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }

    private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            viewPager.setCurrentItem(tab.getPosition());
        }

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

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

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

8. 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" />

9. 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 SherlockFragment {

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

10. 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" />


11. 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 SherlockFragment {

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

12. 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 SherlockFragment {

        @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. 
 It takes a reference to the ViewPager and sets the OnPageChangedListener and the PagerAdapter (implementation will be shown below):
-------------------------------------------------------------------------------------------------------------------
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager())
-------------------------------------------------------------------------
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) {
    }
});
Whats Next? 
We have seen tabs naviagation with actionbar.In the next post we will have a look on dropdown based navigation using action bar
Note!
Our facebook followers hits the "K" mark ie the 1200 Marks  thanks all the followers for such inspiring results.keep liking our page if your face problem comment below .
Please Like,comment,share,tweet,pinit in your style and your ways ! and keep growing our community.

Comments

Alexfollows said…
we started to learn from your blog your actionbarsherlock was simply superb well explained we want to learn actionbarcompact as well might come in next post
Alexfollows said…
Hi i am new to android, can you please help me out with this problem.
How to start the activty in the fragmentPagerAdapter...
I want to start an activity class that i have created in the FragmentAdapter.
When i am calling the activity in the fragment class i am getting error. It is a showing error as "Cannot convert from MyActivity to fragment".
Riya said…
Nice article, I am not able compile it properly ,tried this from this
blog it is not explaining the frag ment properly

Popular posts from this blog

Android Bottom Navigation Bar tutorial with Fragments

Pandas in Python for Data Analysis with Example(Step-by-Step guide)

Pandas in Python - Dataframe Tutorial(With examples)