Simulate Long press by Touch events

Soheil Setayeshi picture Soheil Setayeshi · Jul 27, 2013 · Viewed 8.9k times · Source

How can we simulate long press by touch event? or how can we calculate the time that screen is touched, all in ACTION_DOWN state?

Answer

Soheil Setayeshi picture Soheil Setayeshi · Jul 27, 2013

I have implemented a Touch screen long click finally , thx all:

textView.setOnTouchListener(new View.OnTouchListener() {

    private static final int MIN_CLICK_DURATION = 1000;
    private long startClickTime;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            longClickActive = false;
            break;
        case MotionEvent.ACTION_DOWN:
            if (longClickActive == false) {
                longClickActive = true;
                startClickTime = Calendar.getInstance().getTimeInMillis();
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (longClickActive == true) {
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                if (clickDuration >= MIN_CLICK_DURATION) {
                    Toast.makeText(MainActivity.this, "LONG PRESSED!",Toast.LENGTH_SHORT).show();
                    longClickActive = false;
                }
            }
            break;
        }
        return true;
    }
});

in which private boolean longClickActive = false; is a class variable.