解決 Android中用裏ScrollView 之後 Activity 中的 onTouchEvent 失效問題

失效的原因是因爲 TouchEvent() 首先被 scrollView 中的onTouchEvent() (ScrollView 中也有這個方法) ,而且ScrollView  的 onTouchEvent() 執行完了之後,返回的是 true 所以此時,事件停止傳播。即這個時候 Activity 中的onTouchEvent 將不會被回調了。 所以呢。解決的方法是 自定義一個ScrollView。


例如:


[java] view plaincopy
  1. import android.content.Context;  
  2. import android.util.AttributeSet;  
  3. import android.view.MotionEvent;  
  4. import android.widget.ScrollView;  
  5.   
  6. public class MyScrollView extends ScrollView  
  7. {  
  8.       
  9.     public MyScrollView(Context context)  
  10.     {  
  11.         super(context);  
  12.   
  13.     }  
  14.   
  15.     public MyScrollView(Context context, AttributeSet attrs)  
  16.     {  
  17.         super(context, attrs);  
  18.           
  19.     }  
  20.       
  21.     public MyScrollView(Context context, AttributeSet attrs, int defStyle)  
  22.     {  
  23.         super(context, attrs, defStyle);  
  24.     }  
  25.       
  26.     @Override  
  27.     public boolean onInterceptTouchEvent(MotionEvent event)   //這個方法如果返回 true 的話 兩個手指移動,啓動一個按下的手指的移動不能被傳播出去。  
  28.     {  
  29.         super.onInterceptTouchEvent(event);  
  30.         return false;  
  31.     }  
  32.       
  33.     @Override  
  34.     public boolean onTouchEvent(MotionEvent event)//這個方法如果 true 則整個Activity 的 onTouchEvent() 不會被系統回調  
  35.     {  
  36.         super.onTouchEvent(event);  
  37.         return false;         
  38.     }  
  39.           
  40. }  




自定義了以上代碼之後我們就可以在佈局xml中編寫

[html] view plaincopy
  1. <org.youpackage.name.MyScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:fillViewport="true">  
  5.     <LinearLayout  
  6.          android:layout_width="match_parent"  
  7.          android:layout_height="match_parent"  
  8.          android:orientation="vertical"  
  9.          >   
  10.             ......   //這裏放組件  
  11.     </LinearLayout>  
  12.   
  13.  </org.youpackage.name.MyScrollView 
  14.  
  15.   
  16.  經過這個定義之後 Activity 中的 onTouchEvent() 就回被調用了。  
  17.  有什麼不懂的可以留言。技術最重要就是交流了。 關於事件的傳播,我也是一知半解,如有前輩,望指點一下。 
  18.   轉自:http://blog.csdn.net/failure01/article/details/8525709   
  19.       
發佈了136 篇原創文章 · 獲贊 16 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章