我知道這裏有很多類似的問題,但我無法將答案傳遞給我的問題(或者我沒有找到我需要的答案...)BadTokenException無法在PopUpWindow中添加窗口微調器
在我的actionBar菜單中(onOptionsItemSelected)我打開一個popupWindow用戶設置。複選框,單選按鈕做工精細,但如果在微調我標籤,會出現一個嚴重異常:
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token [email protected] is not valid; is your activity running?
這是onOptionsItemSelected
方法的代碼:
LayoutInflater inflaterSettings = LayoutInflater.from(context);
final LinearLayout llSettings = (LinearLayout) inflaterSettings.inflate(R.layout.actionbar_menu_settings_popup, null);
Spinner spinner = (Spinner) llSettings .findViewById(R.id.spinner_action_settings_intervall_values);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.action_settings_intervall_values, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){ TODO}
@Override
public void onNothingSelected(AdapterView<?> parent) { // TODO }
});
PopupWindow popUp = new PopupWindow(context);
popUp.setContentView(llSettings);
llSettings.post(new Runnable()
{
@Override
public void run()
{
popUp.showAtLocation(llSettings, Gravity.CENTER, 0, 0);
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
width = (int) (width * 0.9);
height = (int) (height * 0.9);
popUp.update(width, height);
}
});
我actionbar_menu_settings_popup.xml:
<Spinner
android:id="@+id/spinner_action_settings_intervall_values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/action_settings_intervall_values" />
和string.xml:
<string-array name="action_settings_intervall_values">
<item>5</item>
<item>15</item>
<item>30</item>
<item>45</item>
<item>60</item>
<item>120</item>
<item>180</item>
</string-array>
編輯
做了一個登錄onOptionsItemSelected
:
Log.i("MainActivity#onCreateOptionsItems", "context: " + context);
Log.i("MainActivity#onCreateOptionsItems", "getApplicationContext: " + getApplicationContext());
Log.i("MainActivity#onCreateOptionsItems", "this: " + this);
結果:
06-21 10:40:58.185: I/MainActivity#onCreateOptionsItems(14463): context: [email protected]
06-21 10:40:58.185: I/MainActivity#onCreateOptionsItems(14463): getApplicationContext: [email protected]
06-21 10:40:58.185: I/MainActivity#onCreateOptionsItems(14463): this: [email protected]
你在哪裏分配上下文? 'onCreate'中的 –
我做了'context = this;' – lis
你的彈出窗口沒有與窗口管理器連接。 – Atrix1987