Sunday, 12 February 2017

Android: Implementing ViewPager

This post is regarding the implementation of ViewPager in Android. ViewPager is basically the layout manager that allows you to flip(swipe) pages of data left or right or you can say with the help of ViewPager you can swipe left or right your view/screen containing some data.
ViewPager is most often used with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.
Let's start the steps to implement a ViewPager:

-Create the Views
Create a layout file fragment_screen_slide_page.xml which will be used for the content of a fragment with the following snippet:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView style="?android:textAppearanceMedium"
        android:padding="16dp"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Your data to be displayed in your view." />
</ScrollView>


-Add a ViewPager
ViewPagers have built-in swipe gestures for transition through pages, and they display screen slide animations by default, so you don't need to create any. ViewPagers use PagerAdapters as a supply for new pages to display, so the PagerAdapter will use the fragment class that we created above.

Create a layout file activity_screen_slide.xml that contains a ViewPager:

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

-Create an activity the does the following:
- Sets the content view to be the layout with the ViewPager.
- Creates a class that extends the FragmentStatePagerAdapter abstract class and implements the getItem() method to supply instances of ScreenSlidePageFragment as new pages. The pager adapter also requires that you implement the getCount() method, which returns the amount of pages the adapter will create (five in the example).
- Hooks up the PagerAdapter to the ViewPager.
- Handles the device's back button by moving backwards in the virtual stack of fragments. If the user is already on the first page, go back on the activity back stack.


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...
public class ScreenSlidePagerActivity extends FragmentActivity {

    private static final int NUM_PAGES = 5;
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;

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

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    /**
     * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
     * sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new ScreenSlidePageFragment();
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}


-Create the Fragment
Create a Fragment class that returns the layout that you just created in the onCreateView() method. You can then create instances of this fragment in the parent activity whenever you need a new page to display to the user:

import android.support.v4.app.Fragment;
...
public class ScreenSlidePageFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_screen_slide_page, container, false);

        return rootView;
    }
}

That's all. You are done with ViewPager. Now run your app and swipe left or right to see changes in your data. You can customize the ViewPager according to your requirements as well.
I'll show you some hacks like page swipe animation in the ViewPager in my next post.




No comments:

Post a Comment