2秒后点击按钮

3
当我点击一个按钮时,另一个按钮应该在2秒后通过编程方式被点击。
Helper.setTimeout(() -> {
    _view.findViewById(R.id.turbineStandBy).performClick();
}, 2000);

当我运行此代码时,出现以下异常:

只有创建视图层次结构的原始线程才能触摸其视图。

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

我认为我需要重写run()方法,但是我该如何在我的setTimeout()方法中做到呢?


这个Helper.setTimeout是什么东西? - hata
@hata “Helper” 是我方法 setTimeout() 的类。你在我的帖子中看到的 setTimeout() 的代码。 - xRay
这是你的原始方法,因此你可以重新定义它而不是覆盖run()方法。 - hata
2个回答

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

1
只有创建视图层次结构的原始线程才能触摸它的视图。该异常告诉您必须在主线程中运行Runnable。为此,您可以使用Looper.getMainLooper或Activity#runOnUIThread(参见runOnUiThread vs Looper.getMainLooper().post in Android)。以下代码是结构示例(您可能仍然需要进行某些修改)。
使用Looper.getMainLooper:
public void setTimeout(Runnable runnable, int delay) {
    new Handler(Looper.getMainLooper()).postDelayed(runnable, delay);
}

使用 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();
}

(注:我不知道你是否应该将static修饰符放在方法中。)
显然,在您的情况下,您想要进行延迟,使用Looper.getMainLooperHandler#postDelayed相结合似乎更明智。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接