Android Toast消息不起作用 [英] Android Toast Messages not working

查看:402
本文介绍了Android Toast消息不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Andengine开发适用于Android的游戏.我有MainActivity类和GameScene类.我在GameActivity中使用Toast消息.它正在工作.

I'm developing a game via Andengine for Android. I have MainActivity class and GameScene class. I use Toast messages in GameActivity. And it is working.

Toast.makeText(this, " Hello World", Toast.LENGTH_SHORT).show();

所以我想在GameScene类中使用Toast消息.但这是行不通的.这是代码:

So I wanna use Toast messages in GameScene class. But it doesn't work. Here is the code:

Toast.makeText(activity, " Hello World", Toast.LENGTH_SHORT).show();

我必须使用活动"而不是本".但这不起作用

I have to use "activity" instead of "this". But it doesn't work

为什么?

当我使用第二个时,发生错误. LogCat: http://s29.postimg.org/k8faj9mdj/Capture.png

when I use second one, an error occurs. LogCat: http://s29.postimg.org/k8faj9mdj/Capture.png

推荐答案

您正在尝试在后台线程中显示Toast.您应该在主UI线程上执行所有UI操作.

You're trying to display a Toast in a background thread. You should do all your UI operations on the main UI thread.

对于初学者来说,异常RuntimeException: Can't create handler inside thread that has not called Looper.prepare()可能有点神秘,但从本质上讲,它告诉您您处于错误的线程中.

The exception RuntimeException: Can't create handler inside thread that has not called Looper.prepare() can be a little cryptic for beginners but essentially it tells you that you're in a wrong thread.

要解决此问题,请将吐司包裹到例如runOnUiThread():

To solve it, wrap the toast to e.g. runOnUiThread():

activity.runOnUiThread(new Runnable() {
  @Override
  public void run() {
    Toast.makeText(...).show();
  }
});

这篇关于Android Toast消息不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆