Wednesday, March 5, 2014

How to swipe between layouts in Android apps

Is it easy to open a new layout by swiping horizontally? Yes, it is. When you want to drag your fingers across the screen to switch view layouts, just follow this code!

First, import the Android support library. Right click on your project in ecplise, go to Android Tools, then select Add Support Library. If you don't see that, go to your SDK manager under the Window menu, and find and download it! Now we have all the resources we need.

Paste this in your oncreate to set up the horizontal swipe:
   MyPagerAdapter adapter = new MyPagerAdapter();
   ViewPager pager = (ViewPager) findViewById(R.id.pager);
   pager.setAdapter(adapter);
   pager.setCurrentItem(0);
//set the opening screen
      
Add this class somewhere after the oncreate:
 public class MyPagerAdapter extends PagerAdapter {
    @Override
    public int getCount() {
        return 2; //set  number of swipe screens here 
    }
    @Override
    public Object instantiateItem(final View collection, final int position) {
        LayoutInflater inflater = (LayoutInflater collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.coffee; //set which layout will show on load
            break;
        case 1:
            resId = R.layout.subway; //what layout swiping shows                 break;
        }
        View view = inflater.inflate(resId, null);
        ((ViewPager) collection).addView(view, 0);
        return view;
     }
    @Override
    public void destroyItem(final View arg0, final int arg1, final Object arg2) {
         ((ViewPager) arg0).removeView((View) arg2);
    }
    @Override
    public boolean isViewFromObject(final View arg0, final Object arg1) {
        return arg0 == ((View) arg1);
    }

}

And put this in the default layout, which is actually never seen because it gets replaced with the first swipe screen
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    </LinearLayout>

1 comment:

  1. perfect example sir, just one correction of a missing ) in LayoutInflater.

    (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    ReplyDelete