我正在尝试使用另一个类(class)的 toast 。
在第 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();
}
我试图从另一个类调用这个 toast,但是当我将该方法设为静态时,它说无法对此方法 getApplicationContext() 进行静态引用。
我通过使用 class2.textToast("");
来访问它
对此的任何建议将不胜感激。谢谢
最佳答案
如果您想提供一个对不同上下文(例如 Activity )有效的方法,请将此上下文作为参数传递。
public static void textToast(String textToDisplay, Context context) { ... }
如果您想从嵌套内部类调用此方法(通常是这种情况),您可以使用 this
作为上下文
public void textToast(String textToDisplay) {
...
Toast toast = Toast.makeText(OuterClass.this, text, duration);
...
}
(或者在外部类中实现 textToast
并通过嵌套内部类中的 OuterClass.this.textToast
调用它)
关于java - 允许从另一个类访问 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5252994/