我希望能够在用户尝试滑动到ViewPager中的下一页时验证该页面并使用canSlideOut弹出错误消息。
两个问题:
每次滑动多次调用canSlideOut
我在页面内有一个带有EditTexts的ListView。不想拦截对他们有意义的事件。
代码:
public class StudentPager extends ViewPager {
PagerActivity mPagerActivity;
public StudentPager(Context context) {
super(context);
}
public StudentPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setPagerActivity(PagerActivity pagerActivity) {
mPagerActivity = pagerActivity;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mPagerActivity.canSlideOut() && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return mPagerActivity.canSlideOut() && super.onInterceptTouchEvent(event);
}
}
答案 0 :(得分:0)
此代码有效,不是很优雅。当canSlideOut返回false时,它会让页面稍微蠕动,我无法找到防止它的方法。
public class StudentPager extends ViewPager {
PagerActivity mPagerActivity;
private boolean mIntercepted;
private boolean mBlockSlideOut;
public StudentPager(Context context) {
super(context);
}
public StudentPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setPagerActivity(PagerActivity pagerActivity) {
mPagerActivity = pagerActivity;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return !mBlockSlideOut && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// The purpose of all this is just to enable blocking of a SlideOut
// via the canSlideOut() call. This isn't quite perfect, because it lets
// the page creep a little, but so far I haven't found a better solution
final int action = event.getAction() & MotionEvent.ACTION_MASK;
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
// This swipe is complete, reset flags
mIntercepted = false;
mBlockSlideOut = false;
}
if (mBlockSlideOut) {
return false;
}
if (!mIntercepted) {
mBlockSlideOut = false;
mIntercepted = super.onInterceptTouchEvent(event);
if (mIntercepted && !mBlockSlideOut) {
// Here's the opportunity to block the slideout.
// Making sure that this gets called only once per swipe,
// because the callback can display a message
mBlockSlideOut = !mPagerActivity.canSlideOut();
}
return mIntercepted && !mBlockSlideOut;
}
return super.onInterceptTouchEvent(event);
}
}