[英]How do I make a toast from a non activity class?
I have a class that I am using to get GPS data within my activity.我有一个课程,我用来在我的活动中获取 GPS 数据。 In the constructor I pass it the activity's context:在构造函数中,我将活动的上下文传递给它:
gpsFetcher = new GPSFetcher(this);
and in the gpsFetcher class I have:在 gpsFetcher 类中,我有:
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!谢谢!
Are you forgetting Toast#show
?你忘记了Toast#show
吗?
Toast toast = Toast.makeText(context, "sometext", Toast.LENGTH_LONG);
toast.show();
您还必须调用show()
:
Toast.makeText(context, "sometext", Toast.LENGTH_LONG).show();
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.然后在您的 MainActivity 或其他活动中,您可以直接使用 Toast。
In my case , I declare a non-activity class NoteDB.就我而言,我声明了一个非活动类 NoteDB。 so I declare public static String S
in the class .所以我在类中声明public static String S
。 (You can change S value in the class. Then in my MainActivity , I announce (您可以在类中更改 S 值。然后在我的 MainActivity 中,我宣布
Toast(MainActivity.this, NoteDB.S ,TOAST.SHORT_LENTGH).show();
It works well.它运作良好。
To display a Toast in a Non-Activity Java class, add the Context in the constructor of the java class要在非活动 Java 类中显示 Toast,请在 Java 类的构造函数中添加 Context
[Here PrizeMethods is my java class] [这里 PrizeMethods 是我的 java 类]
public class PrizeMethods {
Context context;
public PrizeMethods(Context context) {
this.context = context;
}
}
and where you are instancing this class in your activity (making an object of it, using it in your main activity), add the context as a parameter.并在您的活动中实例化此类的位置(制作它的对象,在您的主要活动中使用它),添加上下文作为参数。
Like this:像这样:
PrizeMethods pm=new PrizeMethods(this);
after that inside your java class, you can create a toast like this:在你的java类中之后,你可以像这样创建一个toast:
Toast.makeText(context, "toast inside class!!", Toast.LENGTH_SHORT).show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.