viewpager中添加view和禁止划动切换页面及点击切换页面

今天做了个注册和登录的页面,其中就一个Activity 用viewpager。。然后通过点击来实现注册与登录也面的切换。
首先要让viewpager禁止划动就要重写viewpager的onTouchEvent和onInterceptTouchEvent方法。
代码如下:
public class MyViewpager extends ViewPager {
private boolean isCanScroll = false;//不能滑动
Context context;
public MyViewpager(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;;
}

@Override
public boolean onTouchEvent(MotionEvent arg0) {

// TODO Auto-generated method stub
if (isCanScroll) {
return super.onTouchEvent(arg0);
} else {
return false;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if (isCanScroll) {
return super.onInterceptTouchEvent(arg0);
} else {
return false;
}
}
}

然后布局文件如下:

<app.smarthome.zzd.smarthome.view.MyViewpager
    android:id="@+id/login_viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

</app.smarthome.zzd.smarthome.view.MyViewpager>

最后main的代码如下:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_viewpager);

    mViewPager = (ViewPager) findViewById(R.id.login_viewpager);

    mViewList = new ArrayList<View>();
    View login = getLayoutInflater().inflate(R.layout.activity_register, null);
    mViewList.add(login);
    View register = getLayoutInflater().inflate(R.layout.activity_login2, null);
    mViewList.add(register);

    mRegisterNewAccount = (TextView) login.findViewById(R.id.register_new_account);


    mAdapter = new ViewPagerAdapter();
    mViewPager.setAdapter(mAdapter);
    mViewPager.setCurrentItem(mPreviousPosition);

    mRegisterNewAccount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
        }
    });



}
//适配器
protected class ViewPagerAdapter extends PagerAdapter {

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


    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(mViewList.get(position));
    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(mViewList.get(position));
        return mViewList.get(position);
    }

初学安卓,希望兴趣的伙伴可以一起交流学习!!!

你可能感兴趣的:(viewpager,禁止划动切换)