[英]Allow toast to be accessible from another class
I am trying to use a toast from another class. 我正在尝试使用另一堂课的吐司。
In class 1 I have the toast method: 在第1课中,我有toast方法:
public static void textToast(String textToDisplay)
{
Context context = getApplicationContext();
CharSequence text = textToDisplay;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER, 50, 50);
toast.show();
}
I am trying to call this toast from another class but when I make the method static, it says cannot make a static reference to this method getApplicationContext().
我试图从另一个类中调用此Toast,但是当我将该方法设为静态时,它说无法对该方法
getApplicationContext().
进行静态引用getApplicationContext().
I access it by using class2.textToast("");
我通过使用
class2.textToast("");
访问它
Any advice on this would be appreciated. 任何建议,将不胜感激。 Thanks
谢谢
If you want to provide a method which should be valid for different contexts (eg activities), pass this context as parameter. 如果要提供对不同上下文(例如活动)有效的方法,请将此上下文作为参数传递。
public static void textToast(String textToDisplay, Context context) { ... }
If you want to call this method from nested inner classes (as is often the case), you can use this
as context 如果要从嵌套内部类中调用此方法(通常是这样),则可以
this
用作上下文
public void textToast(String textToDisplay) {
...
Toast toast = Toast.makeText(OuterClass.this, text, duration);
...
}
(or implement textToast
in the outer class and call it via OuterClass.this.textToast
from the nested inner class) (或实现
textToast
在外类,并通过调用它OuterClass.this.textToast
从嵌套内部类)
public void FlesmynToast(Activity fActivity, String fMessage) {
LayoutInflater fInflater = fActivity.getLayoutInflater();
View fView = fInflater.inflate(R.layout.custom_toast (ViewGroup) fActivity.findViewById(R.id.custom_toast_layout_id));
ImageView image = (ImageView) fView.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
TextView fText = (TextView) fView.findViewById(R.id.text);
fText.setText(fMessage);
// Toast...
Toast fToast = new Toast(fActivity.getApplicationContext());
fToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
fToast.setDuration(Toast.LENGTH_LONG);
fToast.setView(fView);
fToast.show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.