Android 如何从不扩展 Activity 的类中显示 Toast 消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11466799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display a Toast message in from a class that doesn't extend Activity
提问by user1513889
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
.
如何创建和显示Toast
来自未扩展Activity
类的类的消息?我在另一个由Activity
.
回答by Blackbelt
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();
}
回答by MobileEvangelist
---------------------- 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.
在 Activity 类中,实现该接口并编写 Toast 方法来显示消息。
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:
示例 NonActivityClass 将如下所示:
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 ----------------------------
-------------------------------- 旧版本 2012 --------------- -------------
You can pass context of that activity to your class by passing value to nonActivity class
您可以通过将值传递给 nonActivity 类来将该活动的上下文传递给您的类
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...
希望这对你有用...