Android Example: How to Implement Horizontal View Swiping with Tabs

The Goal is to implement horizontal View swiping with Tabs in Android like the Google Play Store.

HorizontalViewSwiping

I used the default code from Eclipse.

public class MainActivity extends FragmentActivity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

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

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			Fragment fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			}
			return null;
		}
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
			TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
			dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
			return rootView;
		}
	}

}

 

The Layout XML for the MainActivity:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->

<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:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />

</android.support.v4.view.ViewPager>

 
The Layout XML for the DummyFragment:

 <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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >

<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>

 

Instead of the Dummy Fragment you can create your own Fragments.

Just create a new java class that extends “Fragment”.

You can attach your own Fragments to the “MainActivity” that way:

	@Override
	public Fragment getItem(int position) {
		Fragment fragment = new Fragment();
		switch (position) {
		case 0:
			return fragment = new Fragment1();
		case 1:
			return fragment = new Fragment2();
		case 2:
			return fragment = new Fragment3();
		default:
			break;
		}
		return fragment;

 
That’s all :)

Download complete Project Folder

40 thoughts on “Android Example: How to Implement Horizontal View Swiping with Tabs”

  1. Muchas gracias por este tutorial!
    Me ha funcionado a la perfección y era justo lo que estaba buscando.

    Tanks!

  2. hi again i cant import your project folder to eclipse
    when i import that from android project from existing code there is no project enable in your source folder.
    can you help me

  3. Did you download the project and imported it in Eclipse? Click “File” in the menu panel and “Import” my complete project folder – not only the src folder!

  4. sorrry that i’m a bit confused abt the last part:
    “Just create a new java class that extends “Fragment”.
    You can attach your own Fragments to the “MainActivity” that way:”

    I created two new classes called ABC.java and CDB.java
    so i coded:
    @Override
    public Fragment getItem(int position) {
    Fragment fragment = new Fragment();
    switch (position) {
    case 0:
    return fragment = new ABC();
    break
    case 1:
    return fragment = new CDB();
    break
    default:
    break;
    }
    return fragment;
    }

    But an error occured. but you further tell me how to do that?

  5. you’re not just another blog… you’re much better than others!
    Thank you very much for the simple to understand explanation.

  6. ..thanks for the tutorial. How can i implement this with a cursorloader – i want to have several tabs with each having a different list of products based on their category from a sqlite database – kindly help

  7. I am having problem when ever i move my phone to horizontal application crashed.. App work fine when phone is in vertical shape… please help me how can i solve this problem

  8. Can i add tabs to it. Like the twitter app and the quora android app along with the swipe feature. Please write a tutorial on that too.

  9. Thank-you my friend,

    I’ve been trying to do exactly this for hours. Trouble is I now feel like a complete idiot after been shown how easy it is.

    Keep up the good work.

    Gunney.

  10. Hi. Thank you for the great tutorial. I wanted to ask if in section 1,2,3 we can put activities. And when we swipe, we will change activities? How can I do that? Thank you.

  11. Thanks for the info. You would be better off removing the MainActifity.onCreateOptionsMenu method. It is not essential for the example and might create confusion for beginners.

    1. Hey the very first line gives me an error SectionsPagerAdapter mSectionPagerAdapter; it says it cannot be resolved to a type, ive tried adding many different imports and rebuilding please help! (first time i posted with wrong email)

  12. ……………….Looks like this is a great example…………..

    But the problem is i am new to this developing area..
    i’m a nooob..

    i need a complete/full ready to run sample exmple..

    anybody there to help me?

    1. This works right out of the box! just copy the whole folder into your workspace in eclipse, then, open eclipse and click on create a new android app… with the same name of the folder ( you have to go into the downloaded folder and actually copy the second folder in the hierarchy “SlideView”)
      This will create a project with all the files that you downloaded, there will be some errors, related to your settings of strings not being created, just attend to those errors (eclipse tells you what to do), and voila!! it worked for me like a charm!

  13. Hi thanks for this good example.
    i have question how can i create a horizontalscrollview in this project. i try to do that simply but problem is when user wants to scroll the “horizontal scroll view” page going to next slide. can you show me how can i do that.thanks again.

  14. i am tryng to import ur project. bt while importin its taking project as main activity not as swipeview, so m getting error,, so solution pls

  15. This is a great sample. But I don’t think it’s the same as the Google Play tabs. In Google Play, when you scroll the tabs, the page won’t be changed. The page only be changed when you click on it. Do you have any idea how to implement it in your code? Thanks

    1. You have to return the String.title (section 1, section 2 etc) instead of returning a Fragment.java and create an onClick method to start the activity they clicked on in the scrollable menu.

  16. Great Tutorial…from the past two days i have been trying to implement list view inside fragment(like u told in the last part)..but i am getting errors..
    can u please write a post regarding that..PLZ..PLZ…

  17. Thanks men, This is nice,

    I’m trying to add some functions to your code, I put some onClickListener.

    My problem is, where I’ll put or how can I get what the position of the screen (i.e. if the screen is on 1 or 2 or etc)

    and the when clicked, it will do different task depending on the screen.

    Thanks a lot. :)

  18. Hi,

    I am trying to make the number of swipe page change their names and amount depending on what menu page I have selected.

    for example:

    if I have settings selected it will show section1 and section 2, but I I added a new menu item called settings 2, I only wan to see section3 and section4 swipeable.

    So, I want the number of swipes adaptable to menu options. Any help is appreciated. Thank you.

Leave a Reply

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

* Copy This Password *

* Type Or Paste Password Here *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>