失效的原因是因爲 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() 就回被調用了。
- 有什麼不懂的可以留言。技術最重要就是交流了。 關於事件的傳播,我也是一知半解,如有前輩,望指點一下。
- 轉自:http://blog.csdn.net/failure01/article/details/8525709