这是我的viewPager代码。我想禁用用户在viewPager之间滑动但能够点击它。
这是我的代码;
vp= (ViewPager)header.findViewById(R.id.pager);
vp.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
vp.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent (FistActiivty.this,List.class);
in.putExtra("for","latest");
startActivity(in);
}
});
它禁止用户滑动,但之后onclicklistener无效。
如何让onclicklistener再次运行但禁用用户滑动?
答案 0 :(得分:2)
您需要创建像此一样扩展ViewPager的自定义类
MyViewPager.java
public class MyViewPager extends ViewPager
{
public MyViewPager(Context context)
{
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
}
其次,你需要在xml中进行一次更改,你已经定义了android.support.v4.view.ViewPager
喜欢这个
<YourProjectPackageName.MyViewPager
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
答案 1 :(得分:0)
创建自定义viewpager类:
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
并将其用于您的xml文件:
<mypackage.CustomViewPager
android:id="@+id/myViewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />
答案 2 :(得分:0)
我正在使用它。您需要致电viewPager.setPagingEnabled(false);
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* Created by ksenchy on 2.4.2015.
*/
public class CustomViewPager extends ViewPager {
private boolean enabled = true;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return !enabled || super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return enabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}