Sunday, 17 February 2013

Swipe Tabs with Fragments


In last chapter we had created Tabs with Fragments Now we will have swipe Gesture with our tabs. We still do not have swipe gestures yet.For this we will be using ViewPager You can think ViewPager roughly as a listView in horizontal.

Lets start by adding ViewPager to our layout for MainActivity,we be using code from previous post,


Now replace
<FrameLayout
            android:id="@+android:id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

this with
<android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="1" />
This will make us replace
mTabManager = new TabManager(this, mTabHost, android.R.id.tabcontent);

Notice again here we are again using Androids default Tab content


Now we add ViewPager to our activity
this.mViewPager = (ViewPager) super.findViewById(R.id.viewpager);

ViewPager must have an Adapter similar to the way ListView does. We do not have any functionality to add so we ll keep it simple


public class PagerAdpater extends FragmentPagerAdapter {

 private List<Fragment> fragmentList;

 public PagerAdpater(FragmentManager fm, List<Fragment> fragmentList) {
  super(fm);
  this.fragmentList = fragmentList;
 }

 /*
  * (non-Javadoc)
  * 
  * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
  */
 @Override
 public Fragment getItem(int position) {
  // TODO Auto-generated method stub
  return fragmentList.get(position);
 }

 /*
  * (non-Javadoc)
  * 
  * @see android.support.v4.view.PagerAdapter#getCount()
  */
 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return fragmentList.size();
 }

}
The adapter must extend FragmentPagerAdapter

Our Adapter will also be managing change of Tabs and ViewPager's page so

 implements
  OnTabChangeListener, ViewPager.OnPageChangeListener {
  
 /**
  * Initialise ViewPager
  */
 private void initViewPager() {
  List<Fragment> fragments = new Vector<Fragment>();
  fragments
    .add(Fragment.instantiate(this, FragmentA.class.getName()));
  fragments
    .add(Fragment.instantiate(this, FragmentB.class.getName()));
  this.mPagerAdapter = new PagerAdpater(
    super.getSupportFragmentManager(), fragments);
  this.mViewPager = (ViewPager) super.findViewById(R.id.viewpager);
  this.mViewPager.setAdapter(this.mPagerAdapter);
  this.mViewPager.setOnPageChangeListener(this);
  Constants.log(TAG, "intialiseViewPager");
 }

1 comment:

  1. Thanks. Any chance for tutorial about how to swipe element in a list view? Such as Gmail app?

    ReplyDelete