android – Determine which view is currently being Touched while user Moves finger-ThrowExceptions

Exception or error:

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?

How to solve:

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()){
    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;


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");
                    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
                    return false;

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

Leave a Reply

Your email address will not be published. Required fields are marked *