How to display a Toast message from a class that does not extend Activity

Possible duplicate:
How to make a toast from the non activity class?

How can I create and display a Toast message from a class that has not extended the Activity class? I use this class in another class that extends to Activity .

+6
source share
2 answers

You need a link to the context. you can explicitly pass as parameter when creating your class

 public class MyClass { private static Context context; public MyClass(Context c) { context = c; } public static void showToastMethod() { Toast.makeText(context, "mymessage ", Toast.LENGTH_SHORT).show(); } } 
+12
source

You can pass the context of this activity to your class by passing a value to the nonActivity class

example:

 new NonActivityClass(Activityclass.this) ; 

and as in the answer above

 new MyClass(ActivityClass.this); 

In NonActivityClass

 public class NonActivityClass { public NonActivityClass (Context context) { Toast.makeText(context, "mymessage ", Toast.LENGTH_SHORT).show(); } } 

Hope this works for you ...

+4
source

Source: https://habr.com/ru/post/920394/


All Articles