Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onTouchEvent how to get curret view under finger

Tags:

android

this is my code

public class Main extends Activity {  

    @Override  
    public void onCreate(Bundle savedInstanceState)  
    {  
        super.onCreate(savedInstanceState);   
        LinearLayout rLinear=new LinearLayout(this);  
        rLinear.setId(200);  

        for (int c=0;c<5;c++)  
        {  
            ImageView imEdit = new ImageView(this);  
            imEdit.setId(300+c);  
            imEdit.setImageResource(R.drawable.a);  
            imEdit.setLayoutParams(new LayoutParams(36, 36));  

            rLinear.addView(imEdit);
        }
    }  
}  

Okay, I have this code, I'm adding 5 ImageView to an linear layout at runtime, so far so good, but what i would like to do is, when the user slide his finger over one of them, i would like to change the image, so my question would be, how can i know what's the current imageview under the user finger.??

Thanks.

like image 329
user508412 Avatar asked Dec 12 '22 18:12

user508412


2 Answers

This is what I've used to find a first non-ViewGroup view under finger. It is recursive and uses getGlobalVisibleRect

private View findViewAtPosition(View parent, int x, int y) {
    if (parent instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup)parent;
        for (int i=0; i<viewGroup.getChildCount(); i++) {
            View child = viewGroup.getChildAt(i);
            View viewAtPosition = findViewAtPosition(child, x, y);
            if (viewAtPosition != null) {
                return viewAtPosition;
            }
        }
        return null;
    } else {
        Rect rect = new Rect();
        parent.getGlobalVisibleRect(rect);
        if (rect.contains(x, y)) {
            return parent;
        } else {
            return null;
        }
    }
}

Usage example:

public boolean onTouchEvent(MotionEvent ev) {
    Log.i(TAG, "View under finger: " + findViewAtPosition(getRootView(), (int)ev.getRawX(), (int)ev.getRawY()));
}
like image 189
Pavel Alexeev Avatar answered Jan 21 '23 07:01

Pavel Alexeev


Apply

    rLinear.setOnTouchListener(new OnTouchListener() {@Override
    public boolean onTouch(View v, MotionEvent event) {
        String eventName = "";

        LinearLayout layout = (LinearLayout)v;

        for(int i =0; i< layout.getChildCount(); i++)
        {
            View view = layout.getChildAt(i);


            Rect outRect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());

            if(outRect.contains((int)event.getX(), (int)event.getY()))
            {
                                  Log.d("", view.getId());
            }
        }
    }});

ps: this code button is a mess

like image 23
Garry Avatar answered Jan 21 '23 08:01

Garry