Search code examples
androidbuttonsimulatepressed

Android setPressed behavior


The following code is an attempt to simulate a key stroke:

button1.setPressed(true);
try {
Thread.sleep(500);
} catch(InterruptedException e) {
} 
button1.setPressed(false);

The above does nothing at all to the button, but

button1.setPressed(true);

by itself sets the button to it's pressed state.
Why does the first snippet have no effect on the button?


Solution

  • Late reply, but my guess would be because you are blocking the UI-thread, so it will not update the UI until you've already disabled the pressed state again.

    Instead you could try something like;

    class MyClass extends Activity ... {
      private final Handler _handler = new Handler();
      ...
      void somefunc() {
        button1.setPressed(true);
        _handler.postDelayed(new Runnable() {
          @Override
          public void run() {
            button1.setPressed(false);
          }
        }, 500);
      }
    }
    

    Good luck!