简体   繁体   中英

Static dialog with TextView

what`s wrong with this because I cant compile to apk. Error is Cannot use this in a static context but if I change this to context app freeze when dialog must appear.

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

Logcat error:

 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.access$900(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)

A static method is not associated with any particular instance of a class. It is a method associated with the class itself. Thus this has no meaning in a static method- there is no instance of the class to reference.

If this method is in a class that is a Context (eg an Application subclass or an Activity ), then you can remove the static modifier and use this like you are already trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM