Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which view is currently being Touched while user Moves finger

Tags:

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?

like image 816
bgolson Avatar asked Oct 24 '13 16:10

bgolson


1 Answers

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;
    }
}
like image 101
bgolson Avatar answered Nov 07 '22 04:11

bgolson