RSS

Android : Page Swiping using ViewPager

05 Oct

As a follow up on my last Fragments post, I thought it would be useful to include another Honeycomb feature which is the View Pager that implements for page swiping UI pattern.

In this example, I’ve re-used the Fragment implements from the Tabs post.

Requirements

To implement a Tabbed, using fragments on devices running Android 2.1 or higher, you’ll need to include the Android Compatibility library.  In my example, I’m using Compatibility library v4

Step-by-step

  1. Define the ViewPager layout
  2. Define the FragmentActivity container for the PageViewer
  3. Define the PagerAdapter

The Code

The ViewPager layout

The ViewPager layout (viewpager_layout.xml) simply declares the ViewPager class from the v4 compatibility library.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  >
  <android.support.v4.view.ViewPager
  	android:id="@+android:id/viewpager"
  	android:layout_width="fill_parent"
 	android:layout_height="fill_parent"
  	/>
</LinearLayout>

Defining the FragmentActivty

Our main FragmentActivity is going to host the ViewPager layout viewpager_layout.xml and initialise the ViewPager with an adapter that managers the fragments that are displayed when the user swipes between pages.  In my implementation, I simply instantiate the Fragments upfront and supply them in a list to the

constructor of the PagerAdapter PagerAdaptor.java.

As I mentioned in the intro, I reused the fragment implementations from my previous Fragment post where fragment 1 is Red, fragment 2 is Green and fragment 3 is Blue. After all, the design goal of Fragments is code/UI reuse.

/**
 *
 */
package com.andy.fragments.viewpager;

import java.util.List;
import java.util.Vector;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

import com.andy.R;
import com.andy.fragments.tabs.Tab1Fragment;
import com.andy.fragments.tabs.Tab2Fragment;
import com.andy.fragments.tabs.Tab3Fragment;

/**
 * The <code>ViewPagerFragmentActivity</code> class is the fragment activity hosting the ViewPager
 * @author mwho
 */
public class ViewPagerFragmentActivity extends FragmentActivity{
	/** maintains the pager adapter*/
	private PagerAdapter mPagerAdapter;
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.viewpager_layout);
		//initialsie the pager
		this.initialisePaging();
	}

	/**
	 * Initialise the fragments to be paged
	 */
	private void initialisePaging() {

		List<Fragment> fragments = new Vector<Fragment>();
		fragments.add(Fragment.instantiate(this, Tab1Fragment.class.getName()));
		fragments.add(Fragment.instantiate(this, Tab2Fragment.class.getName()));
		fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
		this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);
		//
		ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
		pager.setAdapter(this.mPagerAdapter);
	}
}

Defining the PagerAdapter

The PagerAdapter class needs to extend FragmentPagerAdapter.  The most basic requirement for us, is to implement getItem(int position) and getCount().

/**
 *
 */
package com.andy.fragments.viewpager;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * The <code>PagerAdapter</code> serves the fragments when paging.
 * @author mwho
 */
public class PagerAdapter extends FragmentPagerAdapter {

	private List<Fragment> fragments;
	/**
	 * @param fm
	 * @param fragments
	 */
	public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
		super(fm);
		this.fragments = fragments;
	}
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
	 */
	@Override
	public Fragment getItem(int position) {
		return this.fragments.get(position);
	}

	/* (non-Javadoc)
	 * @see android.support.v4.view.PagerAdapter#getCount()
	 */
	@Override
	public int getCount() {
		return this.fragments.size();
	}
}

Here is what it looks like as we page from left-to-right:

 
85 Comments

Posted by on October 5, 2011 in Android

 

Tags: , , , ,

85 responses to “Android : Page Swiping using ViewPager

  1. Erik S

    October 5, 2011 at 20:28

    Hey,

    Nice tutorial, however I get an error on this row:

    this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);

    the error is on “PagerAdapter” where it says “Cannot instantiate the type PagerAdapter” do you have any idea how to fix this?

    Cheers

    Erik

     
    • mitchwongho

      October 6, 2011 at 10:36

      Hi Eric,

      Thank you for visiting and your comment.

      My gut instinct would be to ask if you’ve correctly defined the PagerAdapter class or included it on the correct package.

      Best Wishes,
      Mitch

       
    • Atul Bhardwaj

      March 28, 2012 at 10:35

      Rename “PagerAdapter” class to “PagerAdapter1” or something else whatever you want.
      It’s getting error because PagerAdapter is a predefineed java class

       
      • Martze

        April 27, 2012 at 14:51

        Thank you for this comment. I’m trying to implement such with monodroid, and this hint made it work!

         
    • Matt

      April 7, 2012 at 17:54

      I had the same problem – turns out it was a wrongly named file in the Android Manifest.xml.
      Namely the <activity android:name=".PagerAdapter" which needs to be renamed for the class running the fragments.

      @Mitch: Thanks so much for this tutorial! 🙂

       
  2. Dominik Erbsland (@erbsland)

    October 10, 2011 at 07:56

    Fantastic! Thanks so much for this tutorial! I’m searching for something like this for a long time now and this tutorial is actually the first one which worked!
    Thanks a lot 🙂 I’m gonna subscribe now 😉

     
    • mitchwongho

      October 10, 2011 at 14:12

      Thanks for visiting, Dominik

       
      • Dominik Erbsland (@erbsland)

        October 12, 2011 at 03:27

        Oh I just came across a problem when trying to further work with your example.
        I wanted to change a few Activities to Fragments so I can slide through them with the PagerAdapter. But when I change the class from “extends Activity” to “extends Fragment” I get a lot of errors in the code.
        For example:
        intent = getIntent();
        or the Toast method
        is not working anymore.
        How can I still pass variables to that fragment like I could do when the class was extending “Activity”?

        Also everywhere I use “this” in the code I get an error now (like in: new TextView(this); )

        Thanks a lot for your help in advance!

         
      • mitchwongho

        October 12, 2011 at 11:34

        Hi Dominik,

        You’ll need to use super.getActivity() to get the FragmentActivity e.g

        super.getActivity.getIntent(); // to get the intent from the ‘parent’

        This also extends for this issue with using ‘this’ as the Context in an Activity.

         
      • Dominik Erbsland (@erbsland)

        October 13, 2011 at 04:13

        Wow, now it works perfectly!
        Thanks so much, Mitch! :-]

         
  3. Nicolas

    October 20, 2011 at 17:25

    hi,
    First, I thank you for this tutorial !!!

    I want to know : How are you doing to change the image from blue to red image (from last layout “tab_frag3” to beginning layout “tab_frag1”) and inverse from first layout to last layout.

    I’m sorry for my english

     
    • mitchwongho

      October 21, 2011 at 00:42

      Hi Nicolas,

      Thank you for visiting and your comment.

      The ViewPager mimics the real World action of paging through a book (right-to-left, left-to-right), so once you reach the last page (fragment), you can’t page further and will need to page back (swipe left-to-right) until you reach the first page (fragment).

      If you are asking how one could implements a carousel (infinite loop), then that would involve manipulating the PagerAdapter to return a x+1 for getCount() and getItem(int position) to perform a modulus operation on the ‘position’ parameter to determine the correct Fragment index in the member variable ‘List fragments’ e.g:

      int i = position % fragments.size();

       
  4. Nicolas

    October 24, 2011 at 10:35

    hi,
    Thank you for answer of my question!

    If I understand, i must just modify the class : PagerAdapter

    Could you tell me where I need to implement “int i=position % fragments.size” ?

     
  5. Nicolas

    October 24, 2011 at 17:06

    Hi,

    In file viewpager_layout.xml, before , i added graphical component .
    In file tab_frag1_jayout.xml, i added button. In the class Tab1Fragment, I defined function (setUpImageView (View v)) to be called each time a click on this button is produced. I would like, from this method, change src parameter of component in viewpager_layout.xml.

    Could you help me ?

     
    • Nicolas

      October 24, 2011 at 17:08

      Sorry,

      In file viewpager_layout.xml, before , i added graphical component .
      In file tab_frag1_jayout.xml, i added button. In the class Tab1Fragment, I defined function (setUpImageView (View v)) to be called each time a click on this button is produced. I would like, from this method, change src parameter of component in viewpager_layout.xml.

      Could you help me ?

       
  6. Nicolas

    October 24, 2011 at 17:08

    Sorry,

    In file viewpager_layout.xml, before android.support.v4.view.ViewPager, i added graphical component .
    In file tab_frag1_jayout.xml, i added button. In the class Tab1Fragment, I defined function (setUpImageView (View v)) to be called each time a click on this button is produced. I would like, from this method, change src parameter of component in viewpager_layout.xml.

    Could you help me ?

     
  7. Nicolas

    October 24, 2011 at 17:10

    Sorry,

    In file viewpager_layout.xml, before android.support.v4.view.ViewPager, i added graphical component ImageView.
    In file tab_frag1_jayout.xml, i added button. In the class Tab1Fragment, I defined function (setUpImageView (View v)) to be called each time a click on this button is produced. I would like, from this method, change src parameter of component ImageView in viewpager_layout.xml.

    Could you help me ?

     
  8. Michal

    November 12, 2011 at 19:04

    Hi. Well explained tutorial, thank you.
    I followed it and now i have 3 fragments inside the viewpager and a few buttons above it. Now, I’d like to have one of the buttons onClick to REPLACE FeaturedFragment to FindFragment. If i use a transaction to replace it, it doesn’t really do what it’s supposed to – FindFragment is added below FeatureedFragment.
    I use something like this:
    Fragment fragment = new FindFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.featured, fragment);
    transaction.commit();

    R.id.featured is inflated in FeaturedFragment class. I also tried transaction.replace(R.id.viewpager, fragment); but it obviously crashes the whole interface.

    What should i use instead of R.id.featured? Or maybe there is another way around without using transactions?

    I’d really appreciate your help. From what i see in the forums i wouldn’t be the only one;)

     
    • mitchwongho

      November 15, 2011 at 11:10

      Hi Michal,

      Thanks for visiting.

      If I’m understanding your question correctly, you’d like to switch to a specific Activity when a button is clicked, right?

      If you know the position of the Activity, you should be able to call something like:

      mViewPager.setCurrentItem(pos);

      where ‘pos’ is the position of the Fragment in the pager.

       
  9. Michal

    November 16, 2011 at 00:26

    Unfortunately not. I was thinking about having 3 pages and removing the fragment on the 2nd page and adding another fragment in its place.

    The problem is similar to one described here: http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager

    Apparently, when you replace a fragment using FragmentTransaction you can’t use the R.id… which you used to inflate a fragment, because the replace method will just add the new fragment under the old one. It’s not very intuitive, but maybe it’s just me?

    So what I ended up doing, was to inflate 3 container layouts with ViewPager getItem method (I’m using simple PagerAdapter instead of FragmentPagerAdapter now) and adding fragments inside these layouts. Then I can use R.id of the container layout on the middle page of ViewPager to replace the fragment.

    What you have to remember though is that viewpager doesn’t inflate these layouts immediately, so you can’t just add these fragments in onCreate method of your Activity. Instead you have to use ViewGroup.OnHierarchyChangeListener to find out if these views are already there.

    I’m relatively new to Android, so I would really like to hear if you find this solution proper. I wasn’t able to come up with anything better. The drawback is that I can’t use FragmentStatePagerAdater’s methods to save the state of the fragment, so I will have to implement my own. But this is relatively small price I think. But maybe you can see other problems? WHat do you think?

     
  10. rully

    December 6, 2011 at 02:09

    thx for to tutor, can u help me,
    i want using

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    in Tab1Fragment but it seems there is something wrong, always appears the method us undefined for the type Tab1Fragment, how do i fix it? help me 🙂

    thx

     
  11. Mitchell

    December 21, 2011 at 00:51

    Great tutorial!

    If I want a ViewPager to occupy only part of the screen, with a couple buttons at the bottom that remain no matter which Fragment the user has swiped to, how do I go about modifying the code?
    Specifically, how do I instantiate the FragmentActivity with one layout and each Fragment with another?

    Thanks a lot.

     
    • mitchwongho

      December 22, 2011 at 16:04

      Hi,

      Thanks for your questions.

      I haven’t tried what you’re asking, but I believe you could achieve the same thing with tab + fragments (i.e positioning the tabs at the bottom).

      Secondly, I’m not understanding your second requirement regarding layouts for the FragmentActivity and it’s child Fragments.

       
  12. Madhav Palshikar

    December 30, 2011 at 16:32

    hey nice post very usefull can you upload the full source code of this tutorial.

    thanx…! gr8 work.

     
  13. Amol Wadekar

    January 3, 2012 at 14:48

    Hi how I can manage orientation in ViewPager.

     
  14. alex.koukla

    January 26, 2012 at 14:15

    can you please provide source code for the infinit paging ?

    Thanx

     
  15. Swami

    February 1, 2012 at 17:16

    Hi,

    Nice post. I am bit confused in using this for my requirement to show a PPT with 20 slides.
    Do I need to precreate the 20 fragments with BitMap image before creating the PagerAdapter. In that case i will end up with memory issues. Is there a way to maintain 3 or 5 fragments(slides) in memory and remove or destroy the old one on swiping.

    regards,
    Swami

     
  16. Adi

    February 10, 2012 at 20:32

    Hey Mitch, firstly, when I spotted this tutorial I was happy because this is what I had been searching for days. I have dissected and understood the working of ViewPager and PagerAdapter to a good extent. I need to use this knowledge for my Reader app but I’m having a problem and I hope you could guide me since I’m new to Android.

    I’m using Android 2.1 to create a text file reader and I’m using a BufferedReader to read a file like this:
    BufferedReader in = new BufferedReader(new FileReader(“/sdcard/TextFiles/post.txt”));

    I cant find a way to organize the data from this file into pages that can be set using addView and thus be displayed. Since these pages are dynamic, my code should be able to split the data into pages based on screen size and then use ViewPager to display. Kindly help!

     
  17. dqtuan9x

    February 18, 2012 at 07:01

    Hi !Thanks so much for this tutorial!
    I have a problem : I want to add a new page to first of ViewPager and I using :
    fragments.add(0,Fragment.instantiate(ViewPagerFragmentActivity.this,Fragment0.class.getName()));
    on onPageSelected event but it’s not work 😦

    Please help me add a new Page to first of ViewPager 😦

     
  18. Boateng

    February 19, 2012 at 11:31

    Great tutorial!
    But i have a problem 😦
    how to add a new page (activity) to first of ViewPager ??
    I try this code :
    pager.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int arg0) {

    fragments.set(0,Fragment.instantiate(ViewPagerFragmentActivity.this,
    Tab3Fragment.class.getName()));
    }
    But it’s not work….
    Please help me

     
  19. MeM

    February 23, 2012 at 00:10

    Man, thank you very much for this tutorial, real useful. I follow your steps and i put my ideia on moving.

    continue with your good tutorials
    Best regards

     
  20. MeM

    February 23, 2012 at 00:37

    I have 1 doubt, i have the exacly same senario as you have here. How i tell to start the activity with the green fragment first?

    app started with: red GREEN blue

    Green is “selected”

     
  21. Joshua Ramirez

    February 25, 2012 at 07:37

    Thank you very much for your time and efforts. You’ve helped out a lot.

     
  22. serg

    March 13, 2012 at 13:21

    Hi, can you update this to have that horizontal scrollable header, like the market app?

     
  23. Dave

    March 21, 2012 at 07:33

    Mitch, could you lend me a hand? I have the following error: “The constructor FragmentPagerAdapter(FragmentManager) is undefined” when I try to execute the following line: super(activity.getFragmentManager()); this line follows my public TabsAdapter(Activity activity, ViewPager pager) { which is extending FragmentPagerAdapter. Here’s my whole code:

    package com.davekelley.polling;

    import java.util.ArrayList;
    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Button;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.ViewPager;
    import android.support.v4.view.ViewPager.OnPageChangeListener;

    public class Polling extends Activity {

    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.pager);
    setContentView(mViewPager);
    final ActionBar bar = getActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayShowTitleEnabled(false);
    bar.setDisplayShowHomeEnabled(false);
    mTabsAdapter = new TabsAdapter(this, mViewPager);
    mTabsAdapter.addTab(bar.newTab().setText(“Simple”),
    LoginFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(“Simple”),
    EconFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(“Simple”),
    PoliticsFragment.class, null);

    if (savedInstanceState != null) {
    bar.setSelectedNavigationItem(savedInstanceState.getInt(“tab”, 0));
    }
    }
    protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(“tab”, getActionBar().getSelectedNavigationIndex());
    }

    public static class TabsAdapter extends FragmentPagerAdapter
    implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final ActionBar mActionBar;
    private final ViewPager mViewPager;
    private final ArrayList mTabs = new ArrayList();

    static final class TabInfo {
    private final Class clss;
    private final Bundle args;

    TabInfo(Class _class, Bundle _args) {
    clss = _class;
    args = _args;
    }
    }

    public TabsAdapter(Activity activity, ViewPager pager) {
    super(activity.getFragmentManager());
    mContext = activity;
    mActionBar = activity.getActionBar();
    mViewPager = pager;
    mViewPager.setAdapter(this);
    mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(ActionBar.Tab tab, Class clss, Bundle args) {
    TabInfo info = new TabInfo(clss, args);
    tab.setTag(info);
    tab.setTabListener(this);
    mTabs.add(info);
    mActionBar.addTab(tab);
    notifyDataSetChanged();
    }

    public int getCount() {
    return mTabs.size();
    }

    public Fragment getItem(int position) {
    TabInfo info = mTabs.get(position);
    return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    public void onPageSelected(int position) {
    mActionBar.setSelectedNavigationItem(position);
    }

    public void onPageScrollStateChanged(int state) {
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
    Object tag = tab.getTag();
    for (int i=0; i<mTabs.size(); i++) {
    if (mTabs.get(i) == tag) {
    mViewPager.setCurrentItem(i);
    }
    }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
    // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
    // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
    // TODO Auto-generated method stub

    }
    }
    }

    Any idea what's going on here and what I can do to fix it? My Fragment classes are very simple at the moment, but will eventually load data from an SQL server (at the meantime, they just return a simple inflated layout).

     
  24. Tom

    March 22, 2012 at 20:01

    Swami,

    great question. Were you able to discover a solution? I am having memory issues with only 12 fragments.
    thanks,

    Tom

     
  25. Rahul Kumar (@Rahul2kumar)

    March 30, 2012 at 10:34

    HI mitchwongho,

    These post is very helpful bro.

    I like you Post. But i want to something like a website…

    mean-like.

    My first screen is login screen after sucessfully login.
    I want to show some different page that is the Dashboard.

    May you Help me .
    How Can i do that.

    Cheer’s
    Rahul Kumar

     
  26. codeskraps

    April 3, 2012 at 19:55

    I implemented the example but I use the method:

    public Fragment getItem(int position) {
    return this.fragments.get(position);
    }

    To get my fragments. I then have a another class which extends Fragment and inflate the fragment based on the position on the adapter:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    int resId = 0;
    switch (position) {
    case 0: resId = R.layout.farleft; break;
    case 1: resId = R.layout.left; break;
    case 2: resId = R.layout.middle; break;
    case 3: resId = R.layout.right; break;
    case 4: resId = R.layout.farright;break;
    }

    return = inflater.inflate(resId, container, false);
    }

    This is the onCreateView looks like, but I’m having trouble getting a handle of the views on each layout to then implement onClickListeners.

    I can do this:

    View v = inflater.inflate(resId, container, false);
    ImageView farleft = (ImageView) v.findViewById(R.id.farleftimage);

    but once I try to set the listener to the ImageView I just keep getting an nullpointerexception

    help!!

     
  27. Steve

    April 12, 2012 at 08:37

    My question is how would one go about replacing the content if a particular event occurs in one of the fragments? For example, let’s say the user does something in Tab1Fragment which fires off an event, the result of which is to instantiate a new fragment and replace Tab1Fragment’s content with that of the new fragment — even better if I can have Tab1Fragment as part of the back stack.

    What’s the best way to approach this?

     
  28. warrior_sam

    May 16, 2012 at 10:05

    Sorry I am a noob to android development. The article was simple and easy to follow but I was not able to run the applicaiton successfully. I downlaoded the source code and tried that as well but it still can not run the application. When I run the application it shows a white screen and then errors out by poping up window to force close the app. I also tried to follow up the comments and tried to fix some problem but still in the same position.

    Please help me thanks 😛

     
  29. andresp21

    May 23, 2012 at 21:23

    Thanks for this great article 🙂 Quick question: isn’t too expensive to create all fragments beforehand, instead of creating them on demand? (like creating them under getItem()) Does your approach make the swipe smoother? Why did you go for that approach?

     
  30. fanf

    May 24, 2012 at 21:39

    Hello,
    thanks for this great tutorial. Do you happen to know how it is possible to modify the content of a fragment after it has been instantiated, but when there are multiple fragments from the same class ? For example, if I replace the initialisePaging() method with :
    fragments.add(Fragment.instantiate(this, TabFragment.class.getName()));
    fragments.add(Fragment.instantiate(this, TabFragment.class.getName()));
    fragments.add(Fragment.instantiate(this, TabFragment.class.getName()));
    how can I modify the elements of the UI in these fragments afterwards ?

     
  31. hwangsugeun

    August 18, 2012 at 21:26

    Tab1Fragment extend Fragment implements KeyEvent.Callback{}
    this Fragment not suppert onKeyDown, onKeyUp event
    What should I do
    hwangsugeun@gmail.com
    please give me Solution
    thank

     
  32. James Wilson (@jamesfaceface)

    September 4, 2012 at 11:57

    Great stuff dude. I wanted to use the same class for each of my fragments though so I needed to pass a bundle into the instantiate method so it may be worth noting that way of doing things.

    Thanks for the good post.

     
  33. ahammad

    September 12, 2012 at 08:01

    thankf for great tutorial 🙂
    i have question how to set new layout with new view, to do something .. like toast .

     
  34. jadebyfield

    October 13, 2012 at 01:06

    Hello, great tutorial. I just have a quick question

    I noticed that you are adding fragments to a list and then using/destroying/reusing them as the user swipes. How would I go about implementing this for photos? Say I have an array of bitmaps that I want the user to be able to swipe through, how would I modify your code to accomplish this?

    Thanks for your time and the great tutorial.

     
  35. Karl

    November 4, 2012 at 01:24

    your file that one could download does not work out of the box.

     
  36. Mohammed Shalgham

    November 5, 2012 at 22:56

    thanks alot
    it’s helped

     
  37. Evgen

    November 11, 2012 at 16:14

    Is it possible to get the full project sample source code for the second example? Would be a great help.

     
  38. codenamezero

    December 1, 2012 at 09:59

    thank you! after 2 weeks of digging all over the web, finally found a tutorial that got my fragment to show up inside the tab!!!!!! OMFG!! ❤

     
  39. Jay

    December 13, 2012 at 20:53

    How would one implement a callback function on the switch?

     
  40. Android Notice Board

    February 4, 2013 at 13:47

    Reblogged this on Android Notice Board.

     
  41. Sheddad Kaid-Salah Ferrón

    March 4, 2013 at 15:57

    Hello.

    Very usefull.

    Thank’s for the post.

     
  42. mcheung0

    March 19, 2013 at 17:04

    Thanks for this!

     
  43. Vaibhavi

    May 29, 2013 at 12:43

    Hi ! Nice blog 🙂
    Can you please explain in detail how can I have exactly two images (not partial) at a time in the view ? By implementing HorizontalScrollor, i am not able to achieve that.

     
    • mitchwongho

      May 30, 2013 at 22:37

      Hi Vaibhavi,

      If I understand what you’re asking, you essentially need to declare a HorizontalScollView child view in the fragment’s viewgroup (eg LinearLayout).

      You’d then add a child LinearLayout to the HorizontalScrollView add the ImageViews to the child LinearLayout

       
  44. amer.salkovic

    June 18, 2013 at 14:01

    hi mitch, I have used this tutorial for fragments and page swiping and it works fine for me. Now I would like to expand my application with ViewPagerIndicator. Do you know how I could do that and what are the necessary changes in the PagerAdapter? Thank you for your help

     
  45. Carlos Santos

    July 19, 2013 at 14:46

    Hello, I have the same doubt as the “Mem” user:

    “How i tell to start the activity with the green fragment first?
    app started with: red GREEN blue
    Green is “selected”

    I tried looking everywhere, but couldn’t find a solution. Thanks in advance.

    Thanks in advance.

     
  46. Carlos Santos

    July 19, 2013 at 15:54

    *EDIT* I found it:

    mPager.setCurrentItem(Constants.FRAGMENT_GREEN);

    in which is of type int.

     
  47. Tom

    July 22, 2013 at 15:03

    pager.setAdapter(this.mPagerAdapter); CRASH … please help

     
  48. PanKaj Pkp

    August 2, 2013 at 10:03

    Thanks Buddy, your Tutorial finally Tech me

     
  49. Rajashri

    November 11, 2013 at 09:30

    hello sir,

    i refer ur code its very usale….i develop a small applicattion by refering your code..i wanted ti]o make it zoomable but i couldnt understand how to use zoom function with view pager plz guide me i m a beginner in android i m awating

    thanks u

     
  50. mubashirmeddekar

    April 28, 2014 at 08:22

    How to do the same vertically.? Say orientation is vertical.. Please help me..

     
  51. Maria

    August 19, 2014 at 14:08

    Thank you a lot!

     
  52. Nadeem Ilyas

    October 1, 2014 at 09:46

    Great example.
    Can you please send me source code of this example on my email address (nadeemilyas19@yahoo.com). I have to integrate it in my final project. I will appreciate your effort. Thanks

     
  53. SHIVA SURYA

    January 20, 2015 at 18:41

    Sir, really awsome working perfectly ! i’m new to android! with background of Node.js scripting !

    thanks from http://www.i-visionblog.com

     

Leave a reply to Vaibhavi Cancel reply