涛锅锅的Android资料Android技术知识Android开发

ViewPager的基本使用

2017-01-07  本文已影响4946人  dayang

一、ViewPager:

二、ViewPager常用方法

三、PagerAdapter类

PagerAdapter类是与ViewPager配合使用的适配器类
ViewPager将调用PagerAdapter来取得所需显示的页,而PagerAdapter也会在数据变化时,通知ViewPager。

获取ViewPager实际绘制的列表项的数量

当前项离开屏幕时回调本方法,在本方法中需要将当前想从ViewPager中移除;

获取当前列表项,也就是正在显示的当前页,当前ViewPager所在的位置;

判断view和obj是否为同一个view

四、使用ViewPager

ViewPager的使用跟ListView的使用步骤相似

1.准备布局文件
<?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"
    tools:context="cn.ucai.viewpager.MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/vpGoods"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
2.准备数据源
3.填充适配器
java代码
public class MainActivity extends AppCompatActivity {
    ViewPager mvpGoods;
    ArrayList<Integer>mGoodsList;
    ArrayList<ImageView> mivGoodsList;
    GoodsAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView(){
         //准备数据源
        mGoodsList=new ArrayList<>();
        mGoodsList.add(R.drawable.goods01);
        mGoodsList.add(R.drawable.goods02);
        mGoodsList.add(R.drawable.goods03);
        mGoodsList.add(R.drawable.goods04);
        mGoodsList.add(R.drawable.goods05);

        mivGoodsList=new ArrayList<>();
        for(int i=0;i<mGoodsList.size();i++){
            ImageView iv=new ImageView(this);
           iv.setImageResource(mGoodsList.get(i));
            mivGoodsList.add(iv);
        }
        mAdapter=new GoodsAdapter(this,mivGoodsList);
        mvpGoods= (ViewPager) findViewById(R.id.vpGoods);
        mvpGoods.setAdapter(mAdapter);
    }
  //准备适配器类
    class GoodsAdapter extends PagerAdapter {
        Context context;
        ArrayList<ImageView> ivGoodsList;
        public GoodsAdapter(Context context,ArrayList<ImageView>ivGoodsList){
            this.context=context;
            this.ivGoodsList=ivGoodsList;
        }

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

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public ImageView instantiateItem(ViewGroup container, int position) {
            ImageView imageView=ivGoodsList.get(position);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView imageView=(ImageView)object;
            container.removeView(imageView);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读