失效的原因是因为 TouchEvent() 首先被 scrollView 中的onTouchEvent() (ScrollView 中也有这个方法) ,而且ScrollView 的 onTouchEvent() 执行完了之后,返回的是 true 所以此时,事件停止传播。即这个时候 Activity 中的onTouchEvent 将不会被回调了。 所以呢。解决的方法是 自定义一个ScrollView。
例如:
import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.widget.ScrollView;public class MyScrollView extends ScrollView{ public MyScrollView(Context context) { super(context); } public MyScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public MyScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onInterceptTouchEvent(MotionEvent event) //这个方法如果返回 true 的话 两个手指移动,启动一个按下的手指的移动不能被传播出去。 { super.onInterceptTouchEvent(event); return false; } @Override public boolean onTouchEvent(MotionEvent event) //这个方法如果 true 则整个Activity 的 onTouchEvent() 不会被系统回调 { super.onTouchEvent(event); return false; } }
自定义了以上代码之后我们就可以在布局xml中编写
<org.youpackage.name.MyScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > ...... //这里放组件 </LinearLayout></org.youpackage.name.MyScrollView >
经过这个定义之后 Activity 中的 onTouchEvent() 就回被调用了。
有什么不懂的可以留言。技术最重要就是交流了。 关于事件的传播,我也是一知半解,如有前辈,望指点一下。