Android判断Touch为滑动事件还是操作控件
Android判断Touch为滑动事件还是操作控件
因为在项目中要判断WebView是否处于滚动状态,但它不像ListView有onScrollStateChanged方法来监听,要实现就得手动监听它的Touch事件。
谈起Touch事件不得说提到onInterceptTouchEvent,它是ViewGroup的一个扩展函数,要实现高级效果必不可少的就需要重写onInterceptTouchEvent、对所有的MotionEvent起到一个过滤的作用,最终的目的是防止一些事件传递到它包含的子控件中。
以ScrollView为例介绍滑动滚动条的判定。
@Override
publicbooleanonInterceptTouchEvent(MotionEventev){
/*
*ThismethodJUSTdetermineswhetherwewanttointerceptthemotion.
*Ifwereturntrue,onMotionEventwillbecalledandwedotheactual
*scrollingthere.
*/
/*
*Shortcutthemostrecurringcase:theuserisinthedragging
*stateandheismovinghisfinger.Wewanttointerceptthis
*motion.
*/
finalintaction=ev.getAction();
if((action==MotionEvent.ACTION_MOVE)&&(mIsBeingDragged)){
returntrue;
}
switch(action&MotionEvent.ACTION_MASK){
caseMotionEvent.ACTION_MOVE:{
/*
*mIsBeingDragged==false,otherwisetheshortcutwouldhavecaughtit.Check
*whethertheuserhasmovedfarenoughfromhisoriginaldowntouch.
*/
/*
*Locallydoabsolutevalue.mLastMotionYissettotheyvalue
*ofthedownevent.
*/
finalintactivePointerId=mActivePointerId;
if(activePointerId==INVALID_POINTER){
//Ifwedon'thaveavalidid,thetouchdownwasn'toncontent.
break;
}
//通过activePointerId的值来获得当前触摸点的索引
finalintpointerIndex=ev.findPointerIndex(activePointerId);
//通过索引的值获得当前触摸的y的值
finalfloaty=ev.getY(pointerIndex);
finalintyDiff=(int)Math.abs(y-mLastMotionY);
//根据绝对值和零界点来判断是单击还是滑动滚动条
if(yDiff>mTouchSlop){
mIsBeingDragged=true;
mLastMotionY=y;
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
if(mScrollStrictSpan==null){
mScrollStrictSpan=StrictMode.enterCriticalSpan("ScrollView-scroll");
}
}
break;
}
caseMotionEvent.ACTION_DOWN:{
finalfloaty=ev.getY();
if(!inChild((int)ev.getX(),(int)y)){
mIsBeingDragged=false;
recycleVelocityTracker();
break;
}
/*
*Rememberlocationofdowntouch.
*ACTION_DOWNalwaysreferstopointerindex0.
*/
//记录mLastMotionY和mActivePointerId
//在MotionEvent.ACTION_MOVE状态时会用到
mLastMotionY=y;
mActivePointerId=ev.getPointerId(0);
initOrResetVelocityTracker();
mVelocityTracker.addMovement(ev);
/*
*Ifbeingflingedandusertouchesthescreen,initiatedrag;
*otherwisedon't.mScroller.isFinishedshouldbefalsewhen
*beingflinged.
*/
mIsBeingDragged=!mScroller.isFinished();
if(mIsBeingDragged&&mScrollStrictSpan==null){
mScrollStrictSpan=StrictMode.enterCriticalSpan("ScrollView-scroll");
}
break;
}
caseMotionEvent.ACTION_CANCEL:
caseMotionEvent.ACTION_UP:
/*Releasethedrag*/
mIsBeingDragged=false;
mActivePointerId=INVALID_POINTER;
recycleVelocityTracker();
if(mScroller.springBack(mScrollX,mScrollY,0,0,0,getScrollRange())){
invalidate();
}
break;
caseMotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
/*
*Theonlytimewewanttointerceptmotioneventsisifweareinthe
*dragmode.
*/
returnmIsBeingDragged;
}