SilverBlue SilverBlue - 1 year ago 83
Android Question

The OnLongClickListener don't works

I have a drag and drop code. If the user touch the item, the


Code starts:

View.OnTouchListener dragListener = new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent motionEvent) {
// start move on a touch event
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
// API 24
// view.startDragAndDrop(data, shadowBuilder, view, View.DRAG_FLAG_GLOBAL); // API 24
return true;
return false;

But I would have a
on my code. If the item was hold (long clicked) by the user, a toast messages was show on the display:

homebutton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View arg0) {
Toast.makeText(UserArea.this, "laaaange geklickt", Toast.LENGTH_SHORT).show();
return true;

But it doesn't work :-(

Answer Source

Edit your Touch Event and based on threshold you decide the TOuch or Long Press

private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;

public boolean onTouchEvent(MotionEvent ev) {
    switch (ev.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mDownX = ev.getX();
            mDownY = ev.getY();
            isOnClick = true;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            if (isOnClick) {
                Log.i(LOG_TAG, "onClick ");
                //TODO onClick code
        case MotionEvent.ACTION_MOVE:
            if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
                Log.i(LOG_TAG, "movement detected");
                isOnClick = false;
    return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download