可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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();
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
why?
EDITED:
when I use second one, an error occurs.
LogCat:
http://s29.postimg.org/k8faj9mdj/Capture.png
回答1:
You're trying to display a Toast
in a background thread. You should do all your UI operations on the main UI thread.
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.
To solve it, wrap the toast to e.g. runOnUiThread()
:
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(...).show();
}
});
回答2:
There could be two reasons for your code to not work. It's ether your activity parameter is null or...
Short time after you showing the toast the activity is die, in that case it will kill the toast as well, to avoid this you can call activity.getApplicationContext()
like in @Mehmet Seçkin answer.
回答3:
use one of the following
Toast.makeText(getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(),"please Create your Account First", Toast.LENGTH_SHORT).show();
Toast.makeText(GameActivity.this,"please Create your Account First", Toast.LENGTH_SHORT).show();
回答4:
Use:
Toast.makeText(getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show();
or
Toast.makeText(activity.this, " Hello World", Toast.LENGTH_SHORT).show();
回答5:
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show();
try this.
回答6:
Since you asked why; i think you're giving an activity reference as a context to the Toast message, this is why it isn't working.
If you're trying to show a Toast message from outside of an activity, you could try :
Toast.makeText(activity.getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show();
or from the GameActivity
Toast.makeText(GameActivity.this, " Hello World", Toast.LENGTH_SHORT).show();
or from the MainActivity
Toast.makeText(MainActivity.this, " Hello World", Toast.LENGTH_SHORT).show();
回答7:
Since You are calling it from the class. you need to get the context from the activity through the class constructor or else you need to use GetApplicationcontext().
回答8:
Make sure the app you are testing has notifications turned on. That was my story and why toasts weren't working either. I had gone looking for a straight answer and it just happens that toasts are considered part of the notifications. Interesting stuff, I had no clue.