gpt4 book ai didi

android - 如何从输入法服务启动 PopupWindow 或 Dialog?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:24:07 24 4
gpt4 key购买 nike

当我尝试从 InputMethodService 中弹出 PopupWindow(或 Dialog)时出现同样的异常:

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)
...

如果我尝试弹出一个对话框,我会在 ViewRoot.java 的同一行中得到完全相同的异常。这是我的代码(已删节):

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Test Pop-Up"
/>
</LinearLayout>

我已经尝试了上述代码的许多变体,但 PopupWindows 和 Dialogs 总是得到相同的异常。出于某种原因, toast 警报有效。是否有一种特殊的技术可以从 Service(特别是 InputMethodService)而不是 Activity 启动 PopupWindow 或 Dialog?

提前致谢

巴里

最佳答案

实际上我设法做到了,试试这个:

 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();

关于android - 如何从输入法服务启动 PopupWindow 或 Dialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5698700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com