How do I make a toast from a non activity class?

主宰稳场 提交于 2019-11-30 09:12:46

问题


I have a class that I am using to get GPS data within my activity. In the constructor I pass it the activity's context:

gpsFetcher = new GPSFetcher(this);

and in the gpsFetcher class I have:

this.context = c.getApplicationContext();

OR just

this.context = c;

and then I call the toast with:

Toast.makeText(context, "sometext", Toast.LENGTH_LONG);

But it never shows up... Is there something I'm missing? Is it possible?

Thanks!


回答1:


Are you forgetting Toast#show?

Toast toast = Toast.makeText(context, "sometext", Toast.LENGTH_LONG);
toast.show();



回答2:


You must call show() as well:

Toast.makeText(context, "sometext", Toast.LENGTH_LONG).show();




回答3:


I have met the same question but I solved it.!! In the non-activity class , you just announce a "public static String". Then in your MainActivity or other activity , you can directly use Toast.

In my case , I declare a non-activity class NoteDB. so I declare public static String S in the class . (You can change S value in the class. Then in my MainActivity , I announce

Toast(MainActivity.this, NoteDB.S ,TOAST.SHORT_LENTGH).show();

It works well.



来源:https://stackoverflow.com/questions/5543769/how-do-i-make-a-toast-from-a-non-activity-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!