Android swipe tabs

In this Android tip, I am going to show you how to display swipeable tabs on the action bar. The tabs can be swiped left or right. If tabs are created with TabHost, they are not swipeable. To make the tabs swipeable, you need to implements them with ViewPager. The ViewPager needs a class that extends FragmentStatePagerAdapter abstract class to provide pages the tabs. This class has to implements the TabListener, and OnPageChangeListener interfaces to handle tab selection, and page change events (swiping left or right). Typically, pages of the tabs are fragments. Using ViewPager with Fragment is a convenient way to supply and manage the lifecycle of each page.
Now to have an example application on displaying swipeable tabs on the action bar, you create a new project called SwipeableTabs. Then modify the activity_main.xml file to add a ViewPager as shown below.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.swipabletabs.MainActivity" >

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

</RelativeLayout>


Then, you create two fragment classes: LoginTabFragment and SearchTabFragment. They are the pages of the ViewPager.

LoginTabFragment.java file

package com.example.swipabletabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LoginTabFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
  View view=inflater.inflate(R.layout.floginlayout, container, false);
  return view;
  }
}


floginlayout.xml file

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  
<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Login Page"
  />
</LinearLayout>



SearchTabFragment.java file

package com.example.swipabletabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SearchTabFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
  View view=inflater.inflate(R.layout.fsearchlayout, container, false);
  return view;
}
}


fsearchlayout.xml file
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Searcch Page"
  />

</LinearLayout>


In the MainActivity class, you have to create a class called PagerAdapter that extends FragmentStatePagerAdapter and implements TabListener and OnPageChangeListener interface. It is helper class that allows you to add tabs to the action bar, and to display page of a tab when it is selected and when the page is swiped left or right.

package com.example.swipabletabs;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
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;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
   // Setup action bar for tabs
   ActionBar actionBar = getSupportActionBar();
   // Enable navigation tab mode to the action bar
   actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
   // Hide title of the action bar
   actionBar.setDisplayShowTitleEnabled(false);
   ViewPager pager=(ViewPager)findViewById(R.id.pager);
   // Create PagerAdapter instance and add tabs
   PagerAdapter pAdapter=new PagerAdapter(this,actionBar,pager,2);
   pAdapter.addTab(actionBar.newTab().setText("Login"), LoginTabFragment.class);
   pAdapter.addTab(actionBar.newTab().setText("Search"), SearchTabFragment.class);
   // Restore the previous tab
   if(savedInstanceState!=null){
   actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab",0));
   }
}

protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("tab",getSupportActionBar().getSelectedNavigationIndex());
}

// PagerAdater class that extends the FragmentStatePagerAdapter

  private class PagerAdapter extends FragmentStatePagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
  ViewPager mypager;
  ActionBar myactionbar;
  ArrayList<String> myclss;
  ActionBarActivity myactivity;
  int myNPages;
   public PagerAdapter(ActionBarActivity activity, ActionBar abar, ViewPager vpager, int nPages) {
     super(activity.getSupportFragmentManager());
     mypager=vpager;
     mypager.setAdapter(this);
     myactionbar=abar;
     myactivity=activity;
     myclss=new ArrayList<String>(nPages);
     myNPages=nPages;
     mypager.setOnPageChangeListener(this);
   }
  
   public void addTab(Tab tab,Class<?> clss){
   tab.setTag(clss.getName());
     tab.setTabListener(this);     
     myactionbar.addTab(tab);
     myclss.add(clss.getName());
     notifyDataSetChanged();
   }

   @Override
   public Fragment getItem(int pos) {
      return Fragment.instantiate(myactivity, myclss.get(pos));
    
   }

   @Override
   public int getCount() {
     return myNPages;
   }
  
   public void onTabSelected(Tab tab, FragmentTransaction ftIgnore) {
  
   // Select the clicked tab
      for (int i=0; i<myclss.size(); i++) {
           if (myclss.get(i).equals(tab.getTag().toString())) {
             mypager.setCurrentItem(i);             
            
           }
        }
  
   }
   public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    
      }

   public void onTabReselected(Tab tab, FragmentTransaction ft) {
        
      }
   @Override
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  
  
     }
   @Override
     public void onPageScrollStateChanged(int state) {
     }
   @Override
     public void onPageSelected(int position) {
   // Select corresponding tab when swiping left or right
   myactionbar.setSelectedNavigationItem(position);
  
     }
  }


}


Android-swipe-tabs

Posted by: Dara | post date: 10-28-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.