要让滚动视图中的项目响应 onClick 并知道用户何时向下或向上点击了手指,需要一些棘手的编码。此处的解决方案适用于 API 15+。需要注意的关键是滚动视图实际上没有使用 onTouchListener。相反,使用 OnSimpleGestureListener 在项目上检测事件。然而,有趣的是,OnSimpleGestureListener 不存在 onUp 方法,即使 onDown 存在(见图)。要解决onUp,你必须测试onTouchEvent的返回值:
GestureDetector gestureDetector = new GestureDetector(context, new GestureDetectorListItem());
listItem.setOnTouchListener(this.onTouchArticleItem);
private View.OnTouchListener onTouchArticleItem = new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
try
{
boolean state = gestureDetector.onTouchEvent(event);
if ((event.getAction() == android.view.MotionEvent.ACTION_UP) && !state)
{
// Handle up event here.
return true;
}
else if ((event.getAction() == android.view.MotionEvent.ACTION_DOWN) && state)
{
// Handle down event here.
return true;
}
else
return state;
}
catch (Exception ex)
{
Logger.Log(context, ex.getMessage(), Log.ERROR);
return false;
}
}
};
private class GestureDetectorListItem extends GestureDetector.SimpleOnGestureListener
{
public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
public void onLongPress(MotionEvent e)
{
}
public boolean onDoubleTap(MotionEvent e)
{
return false;
}
public boolean onDoubleTapEvent(MotionEvent e)
{
return false;
}
public boolean onSingleTapConfirmed(MotionEvent e)
{
return false;
}
public void onShowPress(MotionEvent e)
{
}
public boolean onDown(MotionEvent e)
{
return true;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, final float distanceX, float distanceY)
{
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
return super.onFling(e1, e2, velocityX, velocityY);
}
}
我在这个解决方案中看到的唯一问题是滚动视图中滚动的项目是否太少。如果项目太少并且用户在滚动视图上按下项目以外的某个位置,则不会检测到向上/向下事件。这在您的应用程序中是否重要是您必须决定的事情。如果需要,那么可能还需要为滚动视图添加一个 onTouchListener。