以Pager的形式填充到ViewPager

1.自定义Pager,设置要返回的View的方法为抽象方法,并将返回的View

2.设置ViewPager的Adapter

关键代码如下:

public  abstract  class BasePager {

    public Activity mActivity;
    public final View view;

    public BasePager(Activity mActivity) {
        this.mActivity = mActivity;
        view = View.inflate(mActivity, R.layout.view_base_pager, null);
        FrameLayout flBase = (FrameLayout) view.findViewById(R.id.fl_base_pager);
        //将子类必须要实现的方法中返回的View填充到FrameLayout
        flBase.addView(initView());
    }

    //定义为抽象方法,子类继承该类必须要实现的方法
    public  abstract  View initView();

    //子类继承该类可实现也可不实现
    public void initData() {

    }
}

public class VPAdapter extends PagerAdapter {
    private Context mContext;
    private List mPagers;

    public VPAdapter(Context mContext, List mPagers) {
        this.mContext = mContext;
        this.mPagers = mPagers;
    }

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

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

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        BasePager basePager = mPagers.get(position); container.addView(basePager.view); return basePager.view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
       container.removeView((View) object);
    }
}
mVpContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                BasePager basePager = pagers.get(position);
                basePager.initData();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
public class HomePager extends BasePager {
    public HomePager(Activity context) {
        super(context);
    }
    @Override
    public View initView() {
        TextView tv=new TextView(mContext);
        tv.setText("首页");
        tv.setTextColor(Color.RED);
        tv.setTextSize(20);
        tv.setGravity(Gravity.CENTER);
        return tv;
    }

    @Override
    public void initData() {
        L.d("首页:initData");
        mTvHeadTitle.setText("首页");
        mIvMenu.setVisibility(View.GONE);
    }
}



Demo源代码: http://download.csdn.net/download/k2514091675/10128472

你可能感兴趣的:(以Pager的形式填充到ViewPager)