开发者

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. 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!


Are you forgetting Toast#show?

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


You must call show() as well:

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.

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.


To display a Toast in a Non-Activity Java class, add the Context in the constructor of the java class

[Here PrizeMethods is my java class]

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:

 Toast.makeText(context, "toast inside class!!", Toast.LENGTH_SHORT).show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜