Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Software debounce for Android buttons

I have a simple ImageButton in my Android program which, when clicked, appends a "0" in a TextView. When this button is long clicked, it is supposed to append "+" in that TextView. The program works fine but I'm facing a typical key bouncing effect. When I long press the button, it do appends a "+", but when I release the button, it also appends a "0". It seems like Android registers a second single click when long click ends. How can I eliminate this? Here's what I'm doing:

ImageButton button0=(ImageButton)V.findViewById(R.id.imageButtonzero);
        button0.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                enterNumber.append("0");

            }
        });
        button0.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                enterNumber.append("+");
                return false;
            }
        });

Thanks for your help!

like image 977
Vinit Shandilya Avatar asked Dec 18 '25 12:12

Vinit Shandilya


1 Answers

You need to return true in the OnLongClickListener, to inform other listeners that the event has been consumed and does not need to be actioned upon further down the line :

button0.setOnLongClickListener(new View.OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        enterNumber.append("+");
        return true;
    }
});

Source of information : Android javadoc

like image 134
2Dee Avatar answered Dec 21 '25 04:12

2Dee