显示来自Application类的Toast消息

编程入门 行业动态 更新时间:2024-10-20 05:27:59
本文介绍了显示来自Application类的Toast消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的应用程序中有几个类.一些是活动,服务和纯Java类.我知道我可以在Activity中显示Toast消息,但我想从纯Java类显示Toast.

I have several classes in my application. Some are Activities, Services and Pure java classes. I know i can display a Toast message from within an Activity but i'd like to display a Toast from a pure java class.

在java类中,我将上下文传递给构造函数,但这似乎没有显示吐司面包.

In the java class i pass a context in to the constructor but this doesn't seem to show the toast.

我已经在Application类中创建了一个方法,该方法将String作为参数,希望我可以使用Application上下文生成Toast,在这里也不高兴.

I have created a method in the Application class that takes a String as an argument, hoping i could generate a Toast using the Application context, no joy here either.

如何从不是服务或活动等的类中生成Toast.

How can i generate a Toast from a class that isn't a service or Activity etc.

public class LoginValidate{ public LoginValidate(Context context) { this.context = context; nfcscannerapplication = (NfcScannerApplication) context .getApplicationContext(); } public void someMethod(){ nfcscannerapplication.showToastMessage(result); } }

.

///然后在我的Application类中

///then in my Application class

public void showToastMessage(String message){ Toast.makeText(this.getApplictionContext(), "Encountered a problem with sending tag: " + message, Toast.LENGTH_LONG).show(); }

推荐答案

首先创建像这样的Application类..

First create Application class like this..

public class ApplicationContext extends Application { /** Instance of the current application. */ private static ApplicationContext instance; /** * Constructor. */ public ApplicationContext() { instance = this; } /** * Gets the application context. * * @return the application context */ public static Context getContext() { if (instance == null) { instance = new ApplicationContext(); } return instance; } /** * display toast message * * @param data */ public static void showToast(String data) { Toast.makeText(getContext(), data, Toast.LENGTH_SHORT).show(); } }

从任何类(例如ApplicationContext.showToast("your string");

当心上下文对象泄漏..

be careful about context object leaking..

更多推荐

显示来自Application类的Toast消息

本文发布于:2023-11-26 18:07:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:消息   Application   Toast

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!