我在Android中有一个ListView,我想为行视图和父ListView本身提供onTouchListeners。我想单独响应单个点击和长按行,但是整个ListView上的flings。 (我可以单独为每个行设置onFling方法,但它不健壮,因为用户可以跨行移动他的手指。)我能够成功地为行和ListView分别设置onTouchListener,但是当我设置两者,ListView侦听器永远不会触发 - 只有行侦听器。无论我在行侦听器的方法中返回true还是false,都是这种情况。是否有人知道如何为视图及其父级触发onTouchListener,因为它们在屏幕上占据相同的像素?
ListView的相关代码:
在onCreate方法中的活动:
mListViewDetector = new GestureDetector(new ListViewGestureListener());
mListViewListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return mListViewDetector.onTouchEvent(event);
}
};
mListView = getListView();
mListView.setOnTouchListener(mListViewListener);
自定义GestureListener类(在活动中定义为嵌套类):
class ListViewGestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.i("ListViewGestureDetector","onFling");
return false;
}
}
Listview中各行的相关代码:
在适配器类的bindView方法中:
TextView textView;
textView.setOnTouchListener(new ListsTextViewOnTouchListener());
自定义onTouchListener类(在适配器类中定义为嵌套类):
class ItemsTextViewOnTouchListener implements OnTouchListener {
public boolean onTouch (View v, MotionEvent event){
switch(event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
//stuff
return false;
case MotionEvent.ACTION_CANCEL:
//stuff
return false;
default:
break;
}
return false;
}
}
答案 0 :(得分:1)
Pvans,
答案有点棘手,但内置了这个功能。onTouchEvent()
处理TouchEvent,无论它是哪个对象都是监听器。然后有两种选择来完成你想要的东西。
1)您可以覆盖父视图上的onInterceptTouchEvent()
并处理您的投掷。我发现这适用于具有较小子视图的大型视图。我不喜欢这种方法用于列表(坦率地说)。 onInterceptTouchEvent()
让Touch远离孩子是很棒的,但如果你这样做,你必须同时处理左/右投掷和水平滚动。
2)你也可以创建一个GestureDetector
,它实际上是一个不可见的叠加(排序)。如果将onTouchEvents转发给它,您仍将获得所需的行为,并且您不必担心手动处理滚动。在这种情况下,您只需将TouchEvent发送给Detector,如果它返回true,则List不执行任何操作,OnFling会执行此操作。如果它返回false,则不处理它,因此它必须属于List或其子项之一。
希望这有帮助, FuzzicalLogic