Download Code

Creating Swipeable Views with Tabs

In this tutorial creating swipeable views you will learn how to create swipe able views with tab layout and fragment in android.I will lead you to build a Time Table android app.Let me give you some information about all the classes which you will use in this tutorial.

Fragment

You can learn about Fragment in detail from this Tutorial.Go through these tutorials about Tabs and Action Bar.

Swipeable Views

Swipeable Views is a horizontal navigation.Allow users to move from one screen to another with simple swipe gesture with good user experience.You can swipe between Tabs,detail view etc.

Fragments Pager Adapter

Fragments Pager Adapter is a subclass of Pager Adapter.It implement Pager Adapter which represent each layout/activity as a fragment.Retain it’s position in fragment manager until user move back to that particular fragment or other fragments.Fragment Pager Adapter is best navigation for fixed numbers of pages/layouts.

View Pager

View Pager is a layout manager used to flip screens of data from left to right vice versa.

Ok let’s start create new android swipeable views application project.

fragment,swipeable views

Next create seven new layouts New > Android XML File with names.

  • Sunday
  • Monday
  • Tuesday
  • Wednesday
  • Thursday
  • Friday
  • Saturday

You can put anything in that just for example i’ll use TextView and set the background color.Each Layout XML should be like this.

fragment,swipeable views

Now next you will create 7 fragments activities for each layout.Open src > package name.Right click New > Class.

fragment,swipeable views

Now extends activity with Fragments class and import it.Now Rigth click go to Source > Override/Implement Methods and select onCreateView() method.Then inflate xml layout.You all classes/activities should look like this.

package androidcodec.timetable;

/*
 * 
 * All Rights Reserved By:Farhan Rasheed
 * 
 * */

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Sunday extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View timeView =  inflater.inflate(R.layout.sunday, container,false);
		return timeView;
	}

}

Now go to you activity_main.xml file.Add View Pager and set width,height to match_parent in that just like this.

fragment,swipeable views

Next go to your MainActivity.java class.By default it will look like this.

package androidcodec.timetable;

/*
 * 
 * All Rights Reserved By:Farhan Rasheed
 * 
 * */


import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends Activity{

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

   
}

But you are not dealing with activity,you are dealing with fragments so you should extends this activity with FragmentActivity class like this.

public class MainActivity extends FragmentActivity{

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

   
}

Next implement actionbar interface with tabListener and import unimplemented methods like this.

public class MainActivity extends FragmentActivity implements ActionBar.TabListener{

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

	@Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

   
}

What to do next.Declare variables of ViewPager,Actionbar,adapter(TimetablePagerAdapter) and string array like this.

public class MainActivity extends FragmentActivity implements ActionBar.TabListener{

	private ViewPager timePager;    // View pager variable
	private TimetablePagerAdapter mAdapter;   // adapter to adapt fragment layout as a tabs with swipeable views
	private ActionBar action;                 // action bar variable
	// string array of days which will set as a title on tabs
	private String[] days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

	@Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

   
}

You will see that TimetablePagerAdapter will be red underlined yet.It’s because you haven’t created this class.So hover cursor over this popup window will be infront of you.Select this named class.Now extends this activity/class with FragmentPagerAdapter.Then import contructor and unimplemented methods.
TimetablePagerAdapter.java

package androidcodec.pager;

/*
 * 
 * All Rights Reserved By:Farhan Rasheed
 * 
 * */

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import androidcodec.timetable.Friday;
import androidcodec.timetable.Monday;
import androidcodec.timetable.Thursday;
import androidcodec.timetable.Tuesday;
import androidcodec.timetable.Wednesday;

public class TimetablePagerAdapter extends FragmentPagerAdapter {

	// public constructor of this class with fragment manager to handle every fragment view
	public TimetablePagerAdapter(FragmentManager fm) {
		super(fm);
		// TODO Auto-generated constructor stub
	}

	// get fragment method to change every fragment when swipe gesture is detected at your screen
	@Override
	public Fragment getItem(int itemIndex) {
		// TODO Auto-generated method stub
		// switching statement to switch between fragments
		switch(itemIndex)
		{
		
		case 0:
			return new Monday();     // monday fragment activity
		case 1:
			return new Tuesday();    // tuesday fragment activity
		case 2: 
			return new Wednesday();   // wednesday fragment activity
		case 3:
			return new Thursday();    // thursday fragment activity
		case 4:
			return new Friday();      // friday fragment activity
		
			
		}
		return null;
	}

	// count total number of fragments or items which should be equal to number of tabs
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return 5;
	}

}

Next go back to MainActivity.java class.Within onCreate() method initialize varibale of View Pager,Action bar , TimetablePagerAdapter.Then set page select lisenter on View pager to select particulr tab with it’s concerning fragment to display.
MainActivity.java

package androidcodec.timetable;

/*
 * 
 * All Rights Reserved By:Farhan Rasheed
 * 
 * */


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import androidcodec.pager.TimetablePagerAdapter;



public class MainActivity extends FragmentActivity implements ActionBar.TabListener{

	private ViewPager timePager;    // View pager variable
	private TimetablePagerAdapter mAdapter;   // adapter to adapt fragment layout as a tabs with swipeable views
	private ActionBar action;                 // action bar variable
	// string array of days which will set as a title on tabs
	private String[] days = {"Monday","Tuesday","Wednesday","Thursday","Friday"};
    @SuppressLint("NewApi") @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // refering id of view pager from xml
        timePager = (ViewPager) findViewById(R.id.pager);
        //refering action bar
        action = getActionBar();
        // initializing variable mAdapter
        mAdapter = new TimetablePagerAdapter(getSupportFragmentManager());
        // setting adapter to view pager
        timePager.setAdapter(mAdapter);
        // setting home button to false because we don't have any home button yet
        action.setHomeButtonEnabled(false);
        // setting navigation mode of action bar to tabs
        action.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        //using for loop to add tab with text and setting tab listener on every tab
        for(String tabName : days){
        	action.addTab(action.newTab().setText(tabName).setTabListener(this));
        }
        
        // view page swipe to select any tab
        
        timePager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				// on changing page setting tab selected
				action.setSelectedNavigationItem(position);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
        
    }

	@Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		timePager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		
	}

   
}

Android Manifest.xml
fragment,swipeable views

Before running this project i want to let you know an important point.You should set that theme which action bar otherwise it will crash on action.setHomeButtonEnabled(false) so be sure about it.

Now Run you android application project.Output should be like this.

fragment,swipeable views

I hope you got everything.

You can also visit Code Project for this kind of example.

Don’t forget to leave your feedback.

Thanks.