Question

I have a button that starts a timer, but I'd like to have the option to start the timer after a delay. To achieve this I've set it up so you can long press on the button and get a dialog with alternative options for how to start the timer.

Button start = (Button)findViewById(R.id.StartStop);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(R.string.PickTimingMethod);
                builder.setItems(R.array.TimeOptions, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(MainActivity.this, i + "", Toast.LENGTH_LONG).show();
                    }
                });
                builder.create().show();
            }
        });

It doesn't behave exactly how I want it to. The long press event doesn't fire until I release my start button. Instead, I would like the long press event to fire after maybe 1 second of being pressed even if you continue to hold the button.

Can I do that with a long click? Or do I need another approach, maybe one with OnTouch?

Was it helpful?

Solution

You should take a look at View.OnLongClickListener, that will do what you want. Like you said, View.OnClickListener will only be fired when you release your finger.

start.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.PickTimingMethod);
        builder.setItems(R.array.TimeOptions, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, i + "", Toast.LENGTH_LONG).show();
            }
        });
        builder.create().show();

        return true;
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top