Search code examples
androidandroid-layouttouch-event

Determine which view is currently being Touched while user Moves finger


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?


Solution

  • 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;
        }
    }