How to determine a long touch on android?

会有一股神秘感。 提交于 2019-12-04 00:49:12

This is how do you normally create an onLongClickListener. Try this:

mapView.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {

            Toast.makeText(mapView.getContext(), "Hello 123", 2000);

            return false;

        }
    });

Reference to your edit:

This might be the way to get what you want.

private final Handler handler = new Handler();
private final Runnable runnable = new Runnable() {
public void run() {
     checkGlobalVariable();
}
};

// Other init stuff etc...

@Override
public void onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
    // Execute your Runnable after 1000 milliseconds = 1 second.
    handler.postDelayed(runnable, 1000);
    mBooleanIsPressed = true;
}

if(event.getAction() == MotionEvent.ACTION_UP) {
    if(mBooleanIsPressed) {
        mBooleanIsPressed = false;
        handler.removeCallbacks(runnable);
    }
}
}

And now you can check with checkGlobalVariable function:

if(mBooleanIsPressed == true)

This is how you can handle this case. Good luck.

Your are probably looking for a normal long click? You will have to set your view to be long clickable by adding android:longClickable to your views xml, or by calling setLongClickable(true). Then you can add an OnLongClickListener to the view. I dont know of a way to determine exactly how long the long click is. But the default long click is the same as the google maps long click that you mentioned.

OnLongClickListener

You can set up a longClickListener and a touchListener. Add a boolean class data member variable longClicked and set it to false initially. This is how you can set the longClickListener.

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            longClicked = true;
            return false;
        }
    });

For touchListener

    view.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(longClicked){
                //Do whatever you want here!!
                longClicked = false;
            }
            return false;
        }
    });

It will give you the same effect as google maps long click. Hope it helps.

user1884608

use System.currentTimeMillis() instead of ev.getEventTime();

When MotionEvent.ACTION_UP, endTime will be set to ev.getEventTime(), this make setting endTime to zero when MotionEvent.ACTION_MOVE be not affect. Instead of setting endTime to zero, you should set startTime to ev.getEventTime()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!