Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get X and Y coordinates onClick

Tags:

android

I used to have an onTouchListener, but I needed to change it to an onClickListener because I didn't want long touches to record different values than short touches. In one of my lines of code, I had X[i]=Integer.valueOf((int)event.getX());, which worked perfectly with an onTouchListener, but with an onClickListener, I get the error event cannot be resolved.

My question is, is there a event.getX() function for an onClickListener?

Here is the portion of my code:

    touchLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            X[i]=Integer.valueOf((int)event.getX());
        }
    });
}

Thanks in advance

like image 480
user3616949 Avatar asked Oct 19 '25 10:10

user3616949


2 Answers

I am pretty sure you cannot get the click x and y coords because OnClick is an event which is triggered by the view's internal implementation of the touch listener. It is triggered when the user lifts his finger and it has not moved more than a certain distance(called touch slop).

On the other hand if you implement your own touch listener, you can detect where the touch gesture started and ended and do whatever you need with these coordinates. It would look something like this:

    view.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                startX = (int) event.getX();
                startY = (int) event.getY();
            }

            if (event.getAction() == MotionEvent.ACTION_UP) {
                int endX = (int) event.getX();
                int endY = (int) event.getY();
                int dX = Math.abs(endX - startX);
                int dY = Math.abs(endY - startY);


                if (Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2)) <= touchSlop) {
                    // Your on click logic here...
                    return true;
                }
            }
       return false;
    }
});

The touchSlop variable here holds how much you can move before the gesture is considered scrolling. You can get this value by calling ViewConfiguration.get(context).getScaledTouchSlop().

like image 57
Veselin Todorov Avatar answered Oct 22 '25 01:10

Veselin Todorov


you may should look this, that may help you:

@Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int)event.getX();
        int y = (int)event.getY();
        switch (event.getAction()) {

            case MotionEvent.ACTION_MOVE:
                 Log.i("222","X-"+x+"===Y="+y);

        }
    return false;
    }
like image 28
Horrorgoogle Avatar answered Oct 22 '25 00:10

Horrorgoogle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!