ViewPager切换View实例

1.在项目中添加V4包

引用v4包中的ViewPager控件。
或者添加android.support.v4.view.ViewPager

2.在activity_main.xml布局中添加ViewPager:


3.创建适配器MyViewPagerAdapter

public class MyViewPagerAdapter extends PagerAdapter {

    private List mListViews;
    public MyViewPagerAdapter(List mListViews) {
        this.mListViews = mListViews;//构造方法,参数是我们的页卡,这样比较方便。
    }
    //直接继承PagerAdapter,至少必须重写下面的四个方法,否则会报错
    @Override
    public void destroyItem(ViewGroup container, int position, Object object)  {
        container.removeView(mListViews.get(position));//删除页卡
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){
        //这个方法用来实例化页卡
        container.addView(mListViews.get(position), 0);//添加页卡
        return mListViews.get(position);
    }
    @Override
    public int getCount() {
        return  mListViews.size();//返回页卡的数量
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0==arg1;//官方提示这样写
    }


}

4.在MainActivity调用

public class MainActivity extends AppCompatActivity {

    private View view1;
    private View view2;
    private View view3;
    private List viewList;
    private ViewPager viewPager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.pager);
        initPager();

    }

    private void initPager() {
        
       LayoutInflater lf = getLayoutInflater().from(this);

        view1 = lf.inflate(R.layout.activity_one, null);
        view2 = lf.inflate(R.layout.activity_two, null);
        view3 = lf.inflate(R.layout.activity_three, null);

        viewList = new ArrayList();// 将要分页显示的View装入数组中
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);

        viewPager.setAdapter(new MyViewPagerAdapter(viewList));


    }
}

你可能感兴趣的:(ViewPager切换View实例)