如何集中创建自定义 Toast
在我的应用程序中,我几乎在所有活动中都使用自定义 toast。要创建自定义吐司,我有以下方法:
private void getCustomToast(String message)
{
LayoutInflater li = getLayoutInflater();
View toastlayout = li.inflate(R.layout.toast_error, (ViewGroup)findViewById(R.id.toast_layout));
TextView text = (TextView) toastlayout.findViewById(R.id.toast_text);
text.setText(message);
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastlayout);
toast.show();
}
它工作正常,但对于每个活动,我需要重复此方法,而不是真正尊重 DRY 原则...
我如何制作一个静态类(例如),其中我有一种在当前活动中触发自定义 toast 的方法?
谢谢
in my application i use a custom toast in almost all the activity. To create the custom toast i have the following method :
private void getCustomToast(String message)
{
LayoutInflater li = getLayoutInflater();
View toastlayout = li.inflate(R.layout.toast_error, (ViewGroup)findViewById(R.id.toast_layout));
TextView text = (TextView) toastlayout.findViewById(R.id.toast_text);
text.setText(message);
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastlayout);
toast.show();
}
It works fine but for each activity I need to duplicate this method, not really respectfull of the DRY principle ...
How can i make a static class (for example) in which i have a method which gonna fire the custom toast on the current activity ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该创建一个包含 toast 方法的自定义抽象 Activity,然后为您的应用程序的活动扩展它:
You should make a custom abstract Activity that contains the toast method, and then extend that for your application's activities:
我想说你可以创建一个接受 Context 对象的 [static] 类。然后使用:
所以在你的静态类中:
或者类似的东西
I want to say you can create a [static] class which will accept a Context object. Then use:
So in your static class:
Or something like that