ViewPager的使用

ViewPager的使用

效果图

这里写图片描述

布局

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    android:scrollbars="none" />

初始化及事件监听

// ViewPager
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
// 添加页面变动的监听事件
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
         @Override
         public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

         }

         @Override
         public void onPageSelected(int position) {
             switch (position) {
                 case 0:
                     // TODO 显示了第一页
                     break;
                 case 1:
                     // TODO 显示了第二页
                     break;
             }
         }

         @Override
         public void onPageScrollStateChanged(int state) {

         }
     });

setOnPageChangeListener比较常用,但是提示API已经过时,还可以用addOnPageChangeListener

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

填充ViewPager

这里填充两个页面,R.layout.viewpager1R.layout.viewpager2 是ViewPager的两个页面的xml

// 添加页面
ArrayList viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
View viewpagerQuotationBtc = View.inflate(getActivity(), R.layout.viewpager1, null);
View viewpagerQuotationLtc = View.inflate(getActivity(), R.layout.viewpager2, null);
viewList.add(viewpagerQuotationBtc);
viewList.add(viewpagerQuotationLtc);
QuotationPageAdapter quotationDataAdapter = new QuotationPageAdapter(viewList);
viewPager.setAdapter(quotationDataAdapter);

Adapter

package ……;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

/**
 * Created by kongqw on 2015/11/25.
 */
public class QuotationPageAdapter extends PagerAdapter {
    private ArrayList<View> mListViews;

    public QuotationPageAdapter(ArrayList<View> mListViews) {
        this.mListViews = mListViews;
    }

    @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 view, Object object) {
        return view == object;
    }
}

设置ViewPager显示第几页

// 显示第一页
mViewPager.setCurrentItem(0);

posted on 2015-12-18 17:49  封起De日子  阅读(165)  评论(0编辑  收藏  举报

导航