希望得到的效果是ListView不能滾動,但是最大的問題在與ListView Item還必有點擊事件,如果不需要點擊事件那就簡單了,直接設置ListView.setEnable(false);
如果還需要點擊事件,滾動與點擊都是在ListView Touch處理機制管理。
ListView點擊事件是復用ViewGroup的處理邏輯,當用戶點擊視圖並且按下與抬起手指之間移動距離很小,滿足點擊事件的時間長度限制,就會觸發點擊事件。
ListView滾動事件是自己處理,有兩個判斷條件,當用戶觸發move事件並且滑動超過touch slop距離 或者 滑動速度超過閥值都會判定為滾動事件。
1 import android.content.Context; 2 import android.util.AttributeSet; 3 import android.view.MotionEvent; 4 import android.widget.ListView; 5 6 public class ScrollDisabledListView extends ListView { 7 8 private int mPosition; 9 10 public ScrollDisabledListView(Context context) { 11 super(context); 12 } 13 14 public ScrollDisabledListView(Context context, AttributeSet attrs) { 15 super(context, attrs); 16 } 17 18 public ScrollDisabledListView(Context context, AttributeSet attrs, int defStyle) { 19 super(context, attrs, defStyle); 20 } 21 22 @Override 23 public boolean dispatchTouchEvent(MotionEvent ev) { 24 final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK; 25 26 if (actionMasked == MotionEvent.ACTION_DOWN) { 27 // 記錄手指按下時的位置 28 mPosition = pointToPosition((int) ev.getX(), (int) ev.getY()); 29 return super.dispatchTouchEvent(ev); 30 } 31 32 if (actionMasked == MotionEvent.ACTION_MOVE) { 33 // 最關鍵的地方,忽略MOVE 事件 34 // ListView onTouch獲取不到MOVE事件所以不會發生滾動處理 35 return true; 36 } 37 38 // 手指抬起時 39 if (actionMasked == MotionEvent.ACTION_UP 40 || actionMasked == MotionEvent.ACTION_CANCEL) { 41 // 手指按下與抬起都在同一個視圖內,交給父控件處理,這是一個點擊事件 42 if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) { 43 super.dispatchTouchEvent(ev); 44 } else { 45 // 如果手指已經移出按下時的Item,說明是滾動行為,清理Item pressed狀態 46 setPressed(false); 47 invalidate(); 48 return true; 49 } 50 } 51 52 return super.dispatchTouchEvent(ev); 53 } 54 }
(轉自:http://blog.csdn.net/androiddevelop/article/details/38815493)