Android Toast Messages not working

2020-07-11 10:01发布

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

8条回答
一纸荒年 Trace。
2楼-- · 2020-07-11 10:30

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().

查看更多
Root(大扎)
3楼-- · 2020-07-11 10:32

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();
查看更多
登录 后发表回答