Possible Duplicate:
How do I make a toast from a non activity class?
How can I create and show a Toast
message from a class which does not extended the Activity
class? I'm using this class in another class that is extended by Activity
.
You need a context Reference. Just have a helper method like
public static void showToastMethod(Context context) {
Toast.makeText(context, "mymessage ", Toast.LENGTH_SHORT).show();
}
---------------------- New Modular Version ------------------------
Create an Interface
public interface ShowToast {
public onShowToast (String message); [additionally you can pass toast duration]
}
In Activity class, implement this interface and write Toast method to show message.
public class ActivityClass extends Activity implements ShowToast{
public giveCallToNonActivityClass(){
new NonActivityClass(this); //Here we're passing interface impl reference.
}
public onShowToast (String message) {
Toast.makeText(ActivityClass.this, message, Toast.LENGTH_SHORT).show();
}
}
Sample NonActivityClass will look like:
public class NonActivityClass {
public NonActivityClass (ShowToast interfaceImpl) {
interfaceImpl.onShowToast("I'm calling Toast from Non Activity ");
}
}
Earlier version was too old to refer. Hope this more modular approach help.
-------------------------------- Old Version 2012 ----------------------------
You can pass context of that activity to your class by passing value to nonActivity class
example:
new NonActivityClass(Activityclass.this) ;
and as in above answer
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With