用户移动手指时确定当前正在触摸的视图

bgo*_*son 17 android touch-event android-layout

我有一个66个视图的网格,如果一个视图被触摸或拖动/移动我想改变它的背景颜色.

我猜我需要在父ViewGroup上放置一个触摸侦听器,但是如何确定拖动/移动哪个子视图?

bgo*_*son 17

在这里找到我的答案:

Android:仅查看已发布的触摸视图

看起来您必须遍历子视图并手动执行检测以查找触摸当前所在的视图.

这是通过覆盖父LinearLayout上的dispatchTouchEvent来实现的:

LinearLayout parent = new LinearLayout(this.getActivity()){
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int x = Math.round(ev.getX());
        int y = Math.round(ev.getY());
        for (int i=0; i<getChildCount(); i++){
            LinearLayout child = (LinearLayout)row.getChildAt(i);
            if(x > child.getLeft() && x < child.getRight() && y > child.getTop() && y < child.getBottom()){
                //touch is within this child
                if(ev.getAction() == MotionEvent.ACTION_UP){
                    //touch has ended
                }
            }
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)