The following two tabs change content below.
Hi, I have written and developed this site to share my experience and ideas with other colleagues. I also started to prepare interview questions and answers for job seekers. I hope it will help you a lot.

What is Tab?

Tabs enable content organization at a high level, such as switching between views, data sets, or functional aspects of an app.

How to implement Tab into android application?

Basically there is two way which we are going to discuss one by one to enable Tab in android application.

 

Full source code is available here : TabApplication

1. Tab using Action bar:
Action bar tabs offer users a familiar interface for navigating between and identifying sibling screens in your app.
To create tabs using ActionBar, you need to enable NAVIGATION_MODE_TABS, then create several instances of ActionBar.Tab and supply an implementation of the ActionBar.TabListener interface for each one. Here is the code which we can put under onCreate method of Activity:

actionBar = getSupportActionBar();
actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);

ActionBar.TabListener  tabListener = new ActionBar.TabListener() {
    @Override
    public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {

    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {

    }
};
//tabs we can increase/decrease as per our requirement but for this example I am assuming 10 tab
for (int i = 0; i < 10; i++) {
    actionBar.addTab(
            actionBar.newTab()
                    .setText("Tab " + (i + 1))
                    .setTabListener(tabListener));
}

 

So as we know every Tab have different body for content so we are using Swipe View (ViewPager) to achieve this. But before to go ahead I would like to explain about Swipe View:

Swipe views provide lateral navigation between sibling screens such as tabs with a horizontal finger gesture (a pattern sometimes known as horizontal paging). ViewPager is the example of Swipe View.

For adding ViewPager below is the layout code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kpblogs.tabapplication.ActionbarTabActivity">

   <android.support.v4.view.ViewPager
       android:id="@+id/viewPager"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
      
       </android.support.v4.view.ViewPager>

</android.support.constraint.ConstraintLayout>

To maintain multiple views in ViewPager we need to use PagerAdapter. For ViewPager we have two main adapter so showing the difference between them

FragmentPagerAdapter FragmentStatePagerAdapter
This is best when navigating between sibling screens representing a fixed, small number of pages. This is best for paging across a collection of objects for which the number of pages is undetermined. It destroys fragments as the user navigates to other pages, minimizing memory usage.

 

In this example going to use FragmentStatePagerAdapter and creating custom Adapter with name : TabAdapter

public TabAdapter(FragmentManager manager){
    super(manager);
}
@Override
public Fragment getItem(int position) {
    Fragment fragment = new BodyFragment();
    Bundle bundle = new Bundle();
    bundle.putString("id", ""+(position+1));
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public int getCount() {
    return 10;
}

 

Right now for example I am reusing same Fragment but as per your requirement you can create different one also. here is the code of Fragment:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.body_fragment_layout, null, false);
    Bundle bundle = getArguments();
    if(bundle!=null){
        ((TextView)view.findViewById(R.id.title)).setText("Fragment : "+bundle.getString("id"));
    }
    return  view;
}

 

If you notice in Adapter under getItem() was passing the id to show on the fragment. So here under Fragment I am picking that ID and showing in text view.

So now integrate Adapter with ViewPager in activity like:

viewPager = (ViewPager)findViewById(R.id.viewPager);
tabAdapter = new TabAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabAdapter);

So now all are ready we just need to take care about Listener so that if we swipe up the pager then tab selected position should be changed. if tab changed then pager layout also should be change.

for action bar listener under onTabSelected update pager using  viewPager.setCurrentItem(tab.getPosition());

@Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
    viewPager.setCurrentItem(tab.getPosition());
}

and for pager setOnPageChangeListener do like this:

viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        getSupportActionBar().setSelectedNavigationItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

 

Note: If we want to hide the title and home menu from ActionBar please try to use below lines of code

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

Now all are ok once you run the app below output will be there :

Actionbar Tab
Actionbar Tab

2. Scrollable Tab using PagerTitleStrip/PagerTabStrip :

Suppose you are not using action bar in your application then no need to worry we can create tab using PagerTitleStrip/PagerTabStrip. To enable tab using this way is very simple.

  1. Add PagerTitleStrip tag under ViewPager like below:
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
       <android.support.v4.view.PagerTitleStrip
           android:id="@+id/pager_title_strip"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_gravity="top"
           android:background="#33b5e5"
           android:textColor="#fff"
           android:paddingTop="4dp"
           android:paddingBottom="4dp" />
        </android.support.v4.view.ViewPager>

2.  And add getPageTitle in Adapter like below:

@Override
public CharSequence getPageTitle(int position) {
            return "Tab "+position;
}

Difference between PagerTitleStrip and PagerTabStrip

PagerTitleStrip PagerTabStrip
PagerTitleStrip is just a strip which contain title texts; it just indicates the title of the section we’re in. PagerTabStrip is very similar to PagerTitleStrip but actually looks like a strip of tabs (it’s used in the Play store tabs, and looks better in my opinion).

Thats it now run the app you will get the tab as below:

Full source code is available here : TabApplication

scrollable tab
scrollable tab

6,319 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *