我有66个视图的网格,如果触摸或拖动/移动视图,我想改变它的背景颜色。
我猜我需要在父ViewGroup上放置一个触摸侦听器,但是如何确定拖动/移动哪个子视图?
答案 0 :(得分:17)
在这里找到我的答案:
Android : Get view only on which touch was released
看起来你必须循环查看子视图并手动点击检测以找到当前触摸的视图。
通过在父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;
}
}
答案 1 :(得分: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。