当我尝试从InputMethodServicepopupPopupWindow(或Dialog)时,我得到了同样的exception:
FATAL EXCEPTION: main android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running? at android.view.ViewRoot.setView(ViewRoot.java:505) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) at android.widget.PopupWindow.invokePopup(PopupWindow.java:828) at android.widget.PopupWindow.showAtLocation(PopupWindow.java:688) at mypackage.MyInputMethodService.onClick(MyInputMethodService.java:123) ...
如果我尝试popup一个Dialog,我会在ViewRoot.java的完全相同的行中得到完全相同的exception。 这是我的代码(删节):public class MyInputMethodService extends InputMethodService implements View.OnClickListener { public void onClick(View v) { // This is the handler for View.OnClickListener LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup_example, null, false), 100, 100, true); pw.showAtLocation(mInputView, Gravity.CENTER, 0, 0); // mInputView was previously created and returned by onCreateInputView() } } // end of MyInputMethodService
和
我已经尝试了上述代码的许多变体,但总是得到PopupWindows和Dialogs的相同exception。 出于某种原因Toast警报工作。 是否有一种特殊的技术可以从服务 (特别是InputMethodService)启动PopupWindow或Dialog,而不是Activity?
提前致谢,
巴里
实际上我设法做到这一点尝试:
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Make your selection"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { // Do something with the selection } }); AlertDialog alert = builder.create(); Window window = alert.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mInputView.getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); alert.show();