android repeat action on pressing and holding a button

There are multiple ways to accomplish this, but a pretty straightforward one would be to post a Runnable on a Handler with a certain delay. In it’s most basic form, it will look somewhat like this:

Button button = (Button) findViewById(R.id.button);
button.setOnTouchListener(new View.OnTouchListener() {

    private Handler mHandler;

    @Override public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (mHandler != null) return true;
            mHandler = new Handler();
            mHandler.postDelayed(mAction, 500);
            break;
        case MotionEvent.ACTION_UP:
            if (mHandler == null) return true;
            mHandler.removeCallbacks(mAction);
            mHandler = null;
            break;
        }
        return false;
    }

    Runnable mAction = new Runnable() {
        @Override public void run() {
            System.out.println("Performing action...");
            mHandler.postDelayed(this, 500);
        }
    };

});

The idea is pretty simple: post a Runnable containing the repeated action on a Handler when the ‘down’ touch action occurs. After that, don’t post the Runnable again until the ‘up’ touch action has passed. The Runnable will keep posting itself to the Handler (while the ‘down’ touch action is still happening), until it gets removed by the touch up action – that’s what enables the ‘repeating’ aspect.

Depending on the actual behaviour of the button and its onclick/ontouch you’re after, you might want to do the initial post without a delay.

Leave a Comment