学習日記--viewpager簡単テスト

2920 ワード

一、javaコード
package com.hxzy.viewpagetest;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnScrollChangeListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private ViewPager mViewPager;

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

		mViewPager = (ViewPager) findViewById(R.id.viewPager);
		MyAdapter adapter = new MyAdapter(this);
		mViewPager.setAdapter(adapter);

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrolled(int position, float arg1, int arg2) {
				if (position == 1 && arg1 > 0) {
					mViewPager.setCurrentItem(0);
				}
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	private class MyAdapter extends PagerAdapter {
		private Context context;
		private ArrayList<ImageView> data;
		private int[] images;

		public MyAdapter(Context context) {
			this.context = context;
			data = new ArrayList<ImageView>();
			images = new int[] { R.drawable.b, R.drawable.c, R.drawable.d };
			for (int i = 0; i < images.length; i++) {
				ImageView image = new ImageView(getApplicationContext());
				image.setImageResource(images[i]);
				data.add(image);
			}
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {

			container.removeView(data.get(position));
		}

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			container.addView(data.get(position));
			return data.get(position);
		}
	}
}

二、layoutレイアウトファイル
<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"
    tools:context="com.hxzy.viewpagetest.MainActivity" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>