Simulate Android button click programmatically

android, java

Solution

Your code is fine. just add `btn.performClick();` after the `invalidate();`

And for better look you can reduce the time of `handler1`.

Problem

I've seen this route, ``` View.performClick(); ``` but it doesn't show the actual press of the button. I've also tried this method, ``` btn.setPressed(true); btn.invalidate(); ``` but, it just shows the button being pressed down. I've narrowed it down to this code, which presses down, and releases, but doesn't click. Am I missing something? How can I do a complete click as if though the user was clicking (monkeyrunner is not an option as of right now) ``` btn = (Button) findViewById(R.id.btn_box); Handler handler = new Handler(); Runnable r = new Runnable() { public void run() { btn.setPressed(true); btn.invalidate(); Handler handler1 = new Handler(); Runnable r1 = new Runnable() { public void run() { btn.setPressed(false); btn.invalidate(); } }; handler1.postDelayed(r1, 1000); } }; handler.postDelayed(r, 1000); ```

Original source

Related problems