1、创建一个activity:
package com.example.huangbaolian.homework3;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.huangbaolian.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hbl on 2017/4/5.
*/
public class T_ViewPVager extends Activity {
private List<Integer> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.work4_tch2);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viePager);
data.add(R.mipmap.img0);
data.add(R.mipmap.img2);
data.add(R.mipmap.img3);
viewPager.setAdapter(new T_ViewPagerAda(this,data));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.e(">>>>>>>","scrolll");
}
@Override
public void onPageSelected(int position) {
Log.e(">>>>>>>","Selected(");
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
2、创建继承view Pager的adapter类;
package com.example.huangbaolian.homework3;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.huangbaolian.R;
import java.util.List;
/**
* Created by hbl on 2017/4/5.
*/
public class T_ViewPagerAda extends PagerAdapter {
private int i = 1;
private Context context;
private LayoutInflater inflater;
private List<Integer> data;
public T_ViewPagerAda(Context context,List<Integer> data) {
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
/**
* 返回页卡数量
* @return
*/
@Override
public int getCount() {
if (data != null) {
return data.size();
}
return 0;
}
/**
* 初始化每个页卡
* @param container
* @param position
* @return
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = inflater.inflate(R.layout.work4_tch1_item_activity,null);
ImageView imageView = (ImageView) view.findViewById(R.id.itm);
imageView.setImageResource(data.get(position));
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == (View)object;
}
}
3、item文件:
<?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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:id="@+id/itm"/>
</LinearLayout>
4、效果图: