Activity 类型中的 runOnUiThread(Runnable) 方法不适用于参数 (void)

发布于 2024-10-28 12:15:07 字数 694 浏览 6 评论 0原文

我试图从非 UI 线程创建一个对话框,在 onUtteranceCompleted():

runOnUiThread(
    new Thread(new Runnable() {
      public void run() { MyDialog.Prompt(this); }
    }).start());

Prompt() 是 MyDialog 类的一个简单的 static 方法:

  static public void Prompt(Activity activity) {
    MyDialog myDialog = new MyDialog();
    myDialog.showAlert("Alert", activity);     
  }

问题是我收到两个错误我正在尝试执行以下操作:

  1. runOnUiThread(Runnable) 方法 在 Activity 类型中不是 适用于参数 (void)
  2. 中的方法 Prompt(Activity) 类型 MyDialog 不适用 对于参数 (new Runnable(){})

我想要的只是通过将对话框创建推迟到 UI 线程来“正确执行”,但似乎我缺少一些基本的东西。

我错过了什么以及如何完成我想要实现的看似简单的任务?

I am trying to create a dialog from a non-UI thread, in onUtteranceCompleted():

runOnUiThread(
    new Thread(new Runnable() {
      public void run() { MyDialog.Prompt(this); }
    }).start());

Prompt() is a simple static method of the class MyDialog:

  static public void Prompt(Activity activity) {
    MyDialog myDialog = new MyDialog();
    myDialog.showAlert("Alert", activity);     
  }

The problem is that I cam getting two errors for what I am trying to do:

  1. The method runOnUiThread(Runnable)
    in the type Activity is not
    applicable for the arguments (void)
  2. The method Prompt(Activity) in the
    type MyDialog is not applicable
    for the arguments (new Runnable(){})

All I wanted is "do it right" by deferring dialog creation to a UI thread, but it appears that I am missing something fundamental.

What am I missing and how do I accomplish the seemingly simple task that I am trying to achieve?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最单纯的乌龟 2024-11-04 12:15:07

它必须是:

runOnUiThread(new Runnable() {
      public void run() { MyDialog.Prompt(NameOfYourActivity.this); }
    });

它表示 不适用于参数 (void) 因为您正在尝试使用 start 方法(这是一个 void 方法)来运行线程。 runOnUiThread 接收一个可运行对象,您不必担心启动它,这是操作系统为您完成的。

关于第二个错误,发生这种情况是因为在该范围内 this 引用了您正在初始化的 Runnable 对象,而不是对 Activity 的引用。因此,您必须明确告知您所指的 this(在本例中为 YourActivityName.this)。

It must be:

runOnUiThread(new Runnable() {
      public void run() { MyDialog.Prompt(NameOfYourActivity.this); }
    });

It says that is not applicable for the arguments (void) because you are trying to run a thread using the start method (which is a void method). runOnUiThread receives a runnable object, and you don't have to worry about starting it, that's done by the OS for you.

With regards to the second error, it happens because in that scope this is referring to the Runnable object that you are initializing, rather than the reference to the activity. So, you have to explicitly tell what this you are referring to (in this case YourActivityName.this).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文