Android ViewPager Demo

In this post, we will create an auto scroll circular view pager with each page a full screen fragment. We will need an Activity class to host the ViewPager view, a Fragment class for the pages in the ViewPager and a FragmentStatePagerAdapter for managing the fragments in the ViewPager. Besides the java classes, we will also need 2 layout files, one for the Activity class and one for the Fragment class.

1. The layout file for the Fragment class, fragment_viewpager_item.xml. This defines the views in each individual page in the ViewPager.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Lucky Number"
        android:textSize="24sp"/>
    <TextView
        android:id="@+id/tv_lucky_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="123"
        android:textSize="40sp"/>
</LinearLayout>

2. The fragment class, ViewPagerFragment.java, this takes the above layout file and create the pages for the ViewPager.

public class ViewPagerFragment extends Fragment {
    public static final String LUCKY_NUMBER = "lucky_number";

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

        TextView tvLuckNum = (TextView) v.findViewById(R.id.tv_lucky_number);
        int luckyNum = getArguments().getInt(LUCKY_NUMBER, 0);
        tvLuckNum.setText(Integer.toString(luckyNum, 10));

        return v;
    }
}

3. The layout file for the activity class, activity_viewpager.xml. This defines the activity view. In this case, it’s just a ViewPager inside a RelativeLayout.

<?xml version="1.0" encoding="utf-8"?>
<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.support.v4.view.ViewPager
        android:id="@+id/vp_auto_scroll_view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"/>
</RelativeLayout>

4. The FragmentStatePagerAdapter class, ViewPagerAdapter.java. This manages the pages in the ViewPagers. It gets the corresponding fragment for the active pages in the ViewPager. For example, when the page in the ViewPager is swiped, it gets the next Fragment and show it on the screen.

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private int[] mLuckyNumbers;

    public ViewPagerAdapter(FragmentManager fm, int[] luckyNumbers) {
        super(fm);
        this.mLuckyNumbers = luckyNumbers;
    }

    @Override
    public Fragment getItem(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(ViewPagerFragment.LUCKY_NUMBER, mLuckyNumbers[position]);
        ViewPagerFragment frag = new ViewPagerFragment();
        frag.setArguments(bundle);

        return frag;
    }

    @Override
    public int getCount() {
        return (mLuckyNumbers == null) ? 0: mLuckyNumbers.length;
    }
}

5. Lastly, the activity class, MainActivity.java. This manages everything in this demo ViewPager app. For demonstration purpose, the data is just a list of 3 numbers, 111, 222, and 333.

public class MainActivity extends AppCompatActivity {

    private ViewPager vpAutoScrollViewPager;
    private int mCurrentPosition = 1;
    private int[] luckyNumbers = {333,111,222,333,111}; // 333,111 at the beginning and the end for circular swipe purpose
    private int lastPageIndex = luckyNumbers.length - 1;
    private Handler autoScrollHandler;

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

        initViewPager();
        initAutoScroll();
    }

    private void initViewPager() {
        vpAutoScrollViewPager = (ViewPager) findViewById(R.id.vp_auto_scroll_view_pager);
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), luckyNumbers);
        vpAutoScrollViewPager.setAdapter(viewPagerAdapter);
        vpAutoScrollViewPager.setCurrentItem(1);
        vpAutoScrollViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position; // Declare mCurrentPosition as a global variable to track the current position of the item in the ViewPager
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // For going from the first item to the last item, Set the current item to the item before the last item if the current position is 0
                if (mCurrentPosition == 0)
                    vpAutoScrollViewPager.setCurrentItem(lastPageIndex - 1, false); // lastPageIndex is the index of the last item, in this case is pointing to the 2nd A on the list. This variable should be declared and initialzed as a global variable

                // For going from the last item to the first item, Set the current item to the second item if the current position is on the last
                if (mCurrentPosition == lastPageIndex)
                    vpAutoScrollViewPager.setCurrentItem(1, false);
            }
        });

        // reset the slider when the ViewPager is scrolled manually to prevent the quick slide after it is scrolled.
        vpAutoScrollViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Log.d("resetAutoScroll", "  MotionEvent.ACTION_UP ");
                    initAutoScroll();
                } else {
                    Log.d("resetAutoScroll", "  MotionEvent>" + event.getAction());
                    if (autoScrollHandler != null) {
                        autoScrollHandler.removeCallbacksAndMessages(null);
                        autoScrollHandler = null;
                    }
                }
                return false;
            }
        });

    }

    // Handler to make the view pager to scroll automatically
    private void initAutoScroll() {
        final int nCount = luckyNumbers.length;
        try {
            if (autoScrollHandler == null) autoScrollHandler = new Handler();
            autoScrollHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    int curPos = vpAutoScrollViewPager.getCurrentItem();
                    curPos++;
                    if (curPos == nCount) curPos = 0;
                    vpAutoScrollViewPager.setCurrentItem(curPos, true);
                    autoScrollHandler.postDelayed(this, 3000); // 3 seconds
                }
            }, 3000);

        } catch (Exception e) {
            Log.d("MainActivity", e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (autoScrollHandler != null) autoScrollHandler.removeCallbacksAndMessages(null);
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search