問題發生環境:
TabAcitivity中的每個tab標籤管理一個ActivityGroup,每個ActivityGroup管理多個Acitivity,
在其中一個Activity中在使用Spinner控制項時,使用代碼:
resolutionSpinner = (Spinner) findViewById(R.id.resolutionSpinner);
resolutionAdapter = ArrayAdapter.createFromResource(this.getParent(), R.array.resolutionItem, android.R.layout.simple_spinner_item);
resolutionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
resolutionSpinner.setAdapter(resolutionAdapter);
點擊Spinner控制項時,系統崩潰,出現如下報錯:
E/AndroidRuntime(26975): FATAL EXCEPTION: main
E/AndroidRuntime(26975): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@4137c7b8 is not valid; is your activity running?
E/AndroidRuntime(26975): at android.view.ViewRootImpl.setView(ViewRootImpl.java:704)
E/AndroidRuntime(26975): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:313)
E/AndroidRuntime(26975): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
E/AndroidRuntime(26975): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
E/AndroidRuntime(26975): at android.view.Window$LocalWindowManager.addView(Window.java:539)
E/AndroidRuntime(26975): at android.app.Dialog.show(Dialog.java:278)
E/AndroidRuntime(26975): at android.app.AlertDialog$Builder.show(AlertDialog.java:932)
E/AndroidRuntime(26975): at android.widget.Spinner$DialogPopup.show(Spinner.java:703)
E/AndroidRuntime(26975): at android.widget.Spinner.performClick(Spinner.java:458)
E/AndroidRuntime(26975): at android.view.View$PerformClick.run(View.java:14325)
E/AndroidRuntime(26975): at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(26975): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(26975): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(26975): at android.app.ActivityThread.main(ActivityThread.java:4512)
E/AndroidRuntime(26975): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(26975): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(26975): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
E/AndroidRuntime(26975): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
E/AndroidRuntime(26975): at dalvik.system.NativeStart.main(Native Method)
問題原因及解決方案:
由報錯可知是彈出的Spinner選項視窗找不到可以依附的context,但我使用的明明是getParent()的上下文,當時奇怪了,糾結了好久,搞了半天,後發現如下網站找到瞭解決方法,原來是載入Acitivity的布局檔案方式導致的,但為什麼會導致這種情況呢?先看看兩種載入方式:
之前使用的是:
onCreate(savedInstanceState);
this.setContentView(R.layout.camera_video1)
修改後:
super.onCreate(savedInstanceState);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.camera_video1, null);
this.setContentView(viewToLoad);
顯然,修改後載入布局檔案方式中使用了this.getParent(),擷取到了上一級context,這樣再彈出子視窗就能找到依附的對象。