How to display a Toast message in from a class that doesn't extend Activity [duplicate]

纵然是瞬间 提交于 2019-11-27 17:52:25

问题


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.


回答1:


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();
  }



回答2:


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



来源:https://stackoverflow.com/questions/11466799/how-to-display-a-toast-message-in-from-a-class-that-doesnt-extend-activity

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