0

When developing Android apps, one often wants to prevent a user from accidentally clicking the same button twice. Otherwise it might happen that two equal activities/fragments are launched (or some other stuff runs twice).

There exist multiple solutions for this issue. For example: maintaining a "last clicked time stamp", disabling views, subclassing buttons...

However, none of these solutions is good. Either it clutters up the activities with boilerplate code, or it is too specific to only one type of view.

I seek a generic solution that satisfies the following requirements:

  • (R1) The double click prevention should require at most one additional line of code.

  • (R2) The double click prevention should be applicable to many different types of views (e.g. Button, MaterialButton,...).

EDIT: I found the activity-based solutions too cluttered. Therefore I wrote a listener-based solution for onClick and onItemClick: https://github.com/fkirc/throttle-click-listener

Mike76
  • 899
  • 1
  • 9
  • 31

1 Answers1

1

Try this

public class MainActivity extends AppCompatActivity {

    private long PressedTime;
    private long Timeout = 500; // Change it to any value you want

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (PressedTime + Timeout > System.currentTimeMillis()) return;
                PressedTime = System.currentTimeMillis();

                // do stuff
            }
        });

        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (PressedTime + Timeout > System.currentTimeMillis()) return;
                PressedTime = System.currentTimeMillis();

                // do stuff
            }
        });


        // .......

    }
}
EMP3R0R
  • 17
  • 2