带有 TextView 的静态对话框

Static dialog with TextView

这有什么问题,因为我无法编译为 apk。错误是 Cannot use this in a static context 但如果我将其更改为 context app freeze 当对话框必须出现时。

public static void mydialog(final Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    TextView myMsg = new TextView(this);
    myMsg.setText("Central");
}

Logcat 错误:

 android.view.WindowLeaked: Activity com.test.testapp.activities.MenuActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{430fc9a8 V.E..... R.....I. 0,0-1048,466} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:457)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:288)
at com.dialog.dialog.showDialog(RateThisApp.java:229)
at com.dialog.dialog.showDialogIfNeeded(RateThisApp.java:108)
at com.test.testapp.activities.MenuActivity.onCreate(MenuActivity.java:47)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access0(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)

static 方法未与 class 的任何特定实例相关联。它是一种与 class 本身相关联的方法。因此 this 在静态方法中没有意义 - 没有 class 的实例可供参考。

如果此方法在 class 中,即 Context(例如 Application subclass 或 Activity),那么您可以删除 static 修饰符并使用 this 就像你已经在尝试做的那样。