I\'m developing an Android 2.2.2 application for a client and he wants to do the following:
Now I have a button with an onClick event but he doesn\'t like, he wants
The event when user releases his finger is MotionEvent.ACTION_UP
. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.
Here's a sample code:
imageButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
// Do what you want
return true;
}
return false;
}
});
for use sample touch listener just you need this code
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, null, 0);
return true;
}
Presumably, if one wants to use an OnTouchListener
rather than an OnClickListener
, then the extra functionality of the OnTouchListener
is needed. This is a supplemental answer to show more detail of how an OnTouchListener
can be used.
Define the listener
Put this somewhere in your activity or fragment.
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
Set the listener
Set the listener in onCreate
(for an Activity) or onCreateView
(for a Fragment).
myView.setOnTouchListener(handleTouch);
Notes
getX
and getY
give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX
and getRawY
if you want the absolute screen coordinates.x
and y
values to determine things like swipe direction.OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:
myView.setOnTouchListener(new View.OnTouchListener()
{
// Implementation;
});