PagerAdapter是基类,该适配器能填充页面内容到ViewPager中。
PageAdapter是一个抽象类。
java.lang.Object
↳ android.support.v4.view.PagerAdapter
要使用PagerAdapter,首先要继承PagerAdapter类,然后至少实现以下方法:
实现父类的两个抽象方法:
@Override
public abstract int getCount ();
@Override
public abstract boolean isViewFromObject (View view, Object object);
重写父类中的两个方法:
@Override
public Object instantiateItem(ViewGroup container, int position) {
return instantiateItem((View) container, position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
destroyItem((View) container, position, object);
}
Demo如下:
布局文件:activity_demo
<?xml version="1.0" encoding="utf-8"?>
<!--activity_demo -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<android.support.v4.view.ViewPager
android:id="@+id/demo_vp_viewPagerDemo"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
/**
* Created by Y_H on 2016/5/17.
* Tip: ViewPage Demo
*/
public class DemoActivity extends Activity {
private ViewPager viewPager;
//存放Image
private List<View> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
viewPager = (ViewPager) findViewById(R.id.demo_vp_viewPagerDemo);
initializeDate();
}
public void initializeDate() {
list = new ArrayList<>();
//图片资源id 数组
int[] resource = {R.drawable.p1, R.drawable.p2, R.drawable.p3};
for (int temp : resource) {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(temp);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
list.add(imageView);
}
DemoAdapter demoAdapter = new DemoAdapter(list);
viewPager.setAdapter(demoAdapter);
}
}
/**
* Created by Y_H on 2016/5/17.
* Tip: ViewPage 适配器
*/
public class DemoAdapter extends PagerAdapter {
List<View> imageList;
public DemoAdapter(List<View> arrayList) {
this.imageList = arrayList;
}
//获得总数量
@Override
public int getCount() {
return imageList.size();
}
//判断是否是同一个对象
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
//将当前视图添加到container中
container.addView(imageList.get(position));
//把当前新添加的视图作为Key传过去
return imageList.get(position);
}
//从当前container中删除指定位置(position)的View;
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(imageList.get(position));
}
}
效果图: