21

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

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

4

2 回答 2

21

在这里找到我的答案:

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;
    }
}
于 2013-10-24T17:17:46.287 回答
1

未经测试,但我认为你可以做类似的事情:ScrollView Inside ScrollView

parentView.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    Log.v(TAG,"PARENT TOUCH");
                    findViewById(R.id.child).getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
                }
            });
            childView.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event)
                {
                    Log.v(TAG,"CHILD TOUCH");
                     //  Disallow the touch request for parent on touch of child view
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    return false;
                }
            });

也许通过简单地遍历所有 childViews,设置 OnTouchListener。

于 2013-10-24T16:22:23.647 回答