Emre Koç
Emre Koç

Reputation: 1381

Can i fire long click event for a view programmatically?

can I fire long click event for a view programmatically ? I know there is performClick() function for firing click event but I'm looking for long click event

Upvotes: 2

Views: 2826

Answers (5)

Nickolay Savchenko
Nickolay Savchenko

Reputation: 1574

public static void longClickView(View v) {

    final int viewWidth = v.getWidth();
    final int viewHeight = v.getHeight();

    final float x = viewWidth / 2.0f;
    final float y = viewHeight / 2.0f;

    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();

    MotionEvent event = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_DOWN, x, y, 0);
    v.onTouchEvent(event);

    eventTime = SystemClock.uptimeMillis();
    final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
    event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE,
            x + touchSlop / 2, y + touchSlop / 2, 0);
    v.onTouchEvent(event);

    v.postDelayed(() -> {
        long eventTime2 = SystemClock.uptimeMillis();
        MotionEvent event2 = MotionEvent.obtain(downTime, eventTime2, MotionEvent.ACTION_UP, x, y, 0);
        v.onTouchEvent(event2);
    }, (long) (ViewConfiguration.getLongPressTimeout() * 1.5f));
}

Upvotes: 0

Eve
Eve

Reputation: 1238

This one worked for me:

view.performLongClick();

Upvotes: 7

Deejaygeekout
Deejaygeekout

Reputation: 242

      view.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {


                //do your stuff here

            return true;
        }
    });

Thats how you do long click in android. or implements onLongClickListener with your parent class then add unimplemented method

with your view.

view.setOnLongClickListener(this);

Upvotes: -1

ElDuderino
ElDuderino

Reputation: 3263

view.performLongClick(); It exists for me...

Upvotes: 3

Bipin Bhandari
Bipin Bhandari

Reputation: 2692

There is no built in function like performClick(). So you will have to implement the system yourself.

You can listen to onTouchListener. Then with the help of event.ACTION_DOWN and event.ACTION_UP determine if the touch is Long key press and perform the action accordingly. Good luck!

Upvotes: -1

Related Questions