Android Toast 消息不起作用 [英] Android Toast Messages not working
问题描述
我正在通过 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
为什么?
当我使用第二个时,发生错误.日志猫: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 the 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屋!