Reputation: 53
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
Upvotes: 4
Views: 13929
Reputation: 301
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().
Upvotes: 14
Reputation: 1518
You can try this
public void onClick(View view) {
int[] values = new int[2];
view.getLocationOnScreen(values);
Log.d("X & Y",values[0]+" "+values[1]);
}
In Method
getLocationOnScreen(values);
you can do whatever you want.If it not work in your case , please let me know
Upvotes: -1
Reputation: 7868
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;
}
Upvotes: 5