Home > Software engineering >  Click on a button after 2 seconds
Click on a button after 2 seconds

Time:11-05

When I click on a button, another button should be clicked programmatically after 2 seconds.

Helper.setTimeout(() -> {
    _view.findViewById(R.id.turbineStandBy).performClick();
}, 2000);

When I run this code, I get this exception:

Only the original thread that created a view hierarchy can touch its views.

public static void setTimeout(Runnable runnable, int delay){
    new Thread(() -> {
        try {
            Thread.sleep(delay);
            runnable.run();
        }
        catch (Exception e){
            System.err.println(e);
        }
    }).start();
}

I think that I have to override the method run() but how can I do that in my setTimeout() method?

CodePudding user response:

  1. Just use post delayed method
  2. button.setOnClickListener(view -> {
          new Handler().postDelayed(new Runnable() {
              @Override
              public void run() {
            //click your button here
    
              }
          },2000);
      });
    

CodePudding user response:

Only the original thread that created a view hierarchy can touch its views.

The exception tells you that you must run the Runnable in the main thread. To do so, you can use Looper.getMainLooper or Activity#runOnUIThread (cf. runOnUiThread vs Looper.getMainLooper().post in Android).

Below codes are structural examples (you might still need to make somewhat modification).

Using Looper.getMainLooper:

public void setTimeout(Runnable runnable, int delay) {
    new Handler(Looper.getMainLooper()).postDelayed(runnable, delay);
}

Using Activity#runOnUIThread:

public void setTimeout(Activity activity, Runnable runnable, int delay) {
    new Thread(() -> {
        try {
            Thread.sleep(delay);
            activity.runOnUIThread(runnable);
        }
        catch (Exception e){
            System.err.println(e);
        }
    }).start();
}

(Note: I don't know whether you should put static modifier to the method or not.)

Apparently, in your case you want to make delay, using Looper.getMainLooper combined with Handler#postDelayed looks smarter.

  • Related