Creating a simple Vertical ViewPager in Android

Android ViewPager is a Layout Manger that allows the user to flip left and right through pages of data. But sometimes we may need to scroll vertically instead of horizontally. Here’s how I created a simple Vertical ViewPager using a ScrollView.

In the layout xml I added four TextViews into the ScrollView. Notice that the android:layout_height is set to 150dip for all childs. So only one child can be visible at once.

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="175dip"
android:layout_height="150dip"
android:layout_gravity="center_vertical"
android:scrollbars="none" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dip"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >

<TextView
android:layout_width="match_parent"
android:layout_height="150dip"
android:layout_gravity="center_horizontal"
android:background="@drawable/ic_launcher"
android:text="Item 1" />

<TextView
android:layout_width="match_parent"
android:layout_height="150dip"
android:layout_gravity="center_horizontal"
android:background="@drawable/ic_launcher"
android:text="Item 2" />

<TextView
android:layout_width="match_parent"
android:layout_height="150dip"
android:layout_gravity="center_horizontal"
android:background="@drawable/ic_launcher"
android:text="Item 3" />

<TextView
android:layout_width="match_parent"
android:layout_height="150dip"
android:layout_gravity="center_horizontal"
android:background="@drawable/ic_launcher"
android:text="Item 4" />
</LinearLayout>
</ScrollView>

In the Activity, I listen for the onFling event and scroll the ScrollView to the correct place using the smoothScrollTo method.

		final int density = (int)getResources().getDisplayMetrics().density;

		mGestureDetector = new GestureDetector(getApplicationContext(),new GestureDetector.SimpleOnGestureListener() {
			int selectedPage=0;
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
				if(velocityY<0){
					selectedPage = Math.min(3, selectedPage+1);
				}else{
					selectedPage = Math.max(0, selectedPage-1);
				}
				mScrollView.smoothScrollTo(0, 150 * density * selectedPage);
				return super.onFling(e1, e2, velocityX, velocityY);
			}

		});

		mScrollView = (ScrollView) findViewById(R.id.scrollView1);
		mScrollView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				mGestureDetector.onTouchEvent(event);
				return true;
			}

		});

The output should look like this,
device-2013-06-26-113321

 

Full Android project can be found here http://www.sendspace.com/file/hz5jyn