21

I have a grid of 66 views and if a view is touched or dragged/moved over I'd like to change it's background color.

I'm guessing I need to put a touch listener on the parent ViewGroup, but how do I determine which child view is being dragged/moved over?

bgolson
  • 3,460
  • 5
  • 24
  • 41

2 Answers2

21

Found my answer here:

Android : Get view only on which touch was released

Looks like you have to loop through the child views and do hit detection manually to find which view the touch is currently over.

Did this by overriding dispatchTouchEvent on the parent LinearLayout:

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;
    }
}
Community
  • 1
  • 1
bgolson
  • 3,460
  • 5
  • 24
  • 41
1

Not tested but I would think you could do something similar to: 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;
                }
            });

Perhaps by simply looping through all your childViews, setting the OnTouchListener.

Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
  • Thanks for your response. The problem is onTouch on the child will only fire if a touch begins within the view. It doesn't react to dragging. I did find a solution and posted above. Thanks again! – bgolson Oct 24 '13 at 17:25