【问题标题】:Click on a button after 2 seconds2秒后点击一个按钮
【发布时间】:2021-11-05 12:16:05
【问题描述】:

当我单击一个按钮时,应在 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 Helper 是我的方法setTimeout() 的类。 setTimeout()的代码你在我的帖子里看到。
  • 这是您的原始方法。所以你可以重新定义它而不是覆盖run() 方法。

标签: java android


【解决方案1】:

只有创建视图层次结构的原始线程才能触及它的 意见。

异常告诉你必须在主线程中运行Runnable。为此,您可以使用Looper.getMainLooperActivity#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.getMainLooper 结合 Handler#postDelayed 看起来更聪明。

【讨论】:

    【解决方案2】:
    1. 只需使用延迟后的方法
    2. button.setOnClickListener(view -> {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
              //click your button here
      
                }
            },2000);
        });
      

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多