在Android中的静态方法中显示Toast

时间:2013-07-23 19:09:41

标签: android methods static toast

我希望在我的静态方法中满足某个条件时向屏幕显示一个Toast,如下所示:

public static void setAuth(String a) {

    String[] nameparts1;

    if (a.trim().isEmpty()) {
        author = "Author's Name";
        firstinit1 = "Initial";
        surname1 = "Surname";
    }

    if (a == 'X') {
        Toast ifx = Toast.makeText(getApplicationContext(), "Please enter name in correct format.", Toast.LENGTH_SHORT);
        ifx.show();
    }
}

然而,这给了我错误:'无法从ContextWrapper'类型中对非静态方法getApplicationContext()进行静态引用。

希望我在这里提供了足够的信息。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:19)

将上下文作为参数传递(在调用中,使用getApplicationContext()作为输入)并在静态函数中使用上下文:

public static void setAuth(String a, Context context) {
...
Toast ifx = Toast.makeText(context, "Please enter name in correct format.", Toast.LENGTH_SHORT);
...
}

在函数调用中

setAuth("Some String",getApplicationContext());

答案 1 :(得分:0)

您必须将上下文作为参数传递给方法

public static void dialog(boolean value, Context context) {
        if (value) {
 Toast.makeText(context, "", Toast.LENGTH_SHORT).show();

}
}