Android 实现ListView不可滚动效果

希望得到的效果是ListView不能滚动,但是最大的问题在与ListView Item还必有点击事件,如果不需要点击事件那就简单了,直接设置ListView.setEnable(false);

如果还需要点击事件,滚动与点击都是在ListView Touch处理机制管理。

ListView点击事件是复用ViewGroup的处理逻辑,当用户点击视图并且按下与抬起手指之间移动距离很小,满足点击事件的时间长度限制,就会触发点击事件。

ListView滚动事件是自己处理,有两个判断条件,当用户触发move事件并且滑动超过touch slop距离 或者 滑动速度超过阀值都会判定为滚动事件。

import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.widget.ListView;public class ScrollDisabledListView extends ListView {private int mPosition;public ScrollDisabledListView(Context context) {super(context);}public ScrollDisabledListView(Context context, AttributeSet attrs) {super(context, attrs);}public ScrollDisabledListView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK;if (actionMasked == MotionEvent.ACTION_DOWN) {// 记录手指按下时的位置mPosition = pointToPosition((int) ev.getX(), (int) ev.getY());return super.dispatchTouchEvent(ev);}if (actionMasked == MotionEvent.ACTION_MOVE) {// 最关键的地方,忽略MOVE 事件// ListView onTouch获取不到MOVE事件所以不会发生滚动处理return true;}// 手指抬起时if (actionMasked == MotionEvent.ACTION_UP|| actionMasked == MotionEvent.ACTION_CANCEL) {// 手指按下与抬起都在同一个视图内,交给父控件处理,这是一个点击事件if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) {super.dispatchTouchEvent(ev);} else {// 如果手指已经移出按下时的Item,,说明是滚动行为,清理Item pressed状态setPressed(false);invalidate();return true;}}return super.dispatchTouchEvent(ev);}}参考资料:

Disable scrolling in Android ListView

Disable scrolling in listview

转载请注明出处:

Android 设置ListView不可滚动

走走停停,不要害怕错过什么,

Android 实现ListView不可滚动效果

相关文章:

你感兴趣的文章:

标签云: