如何从软键盘获取输入文本

J_S*_*ton 11 java android

我正在推出这样的软键盘:

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.toggleSoftInputFromWindow(buttonLayout.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
Run Code Online (Sandbox Code Playgroud)

buttonLayout是我的UI上的一个简单按钮.
如何提取用户写的内容(不使用EditText字段或隐藏EditText),以便用户无法看到或点击它?

Gab*_*han 6

如果没有EditText,你将会遇到困难.

InputMethod需要连接到视图.无论您使用什么视图,都需要覆盖onCreateInputConnection以返回一个自定义InputConnection对象,该对象至少实现commitText(用于单词输入),deleteSurroundingText(用于删除),以及sendKeyEvent(对于假设您处于哑模式的键盘),以及所有完成功能.输入连接是复杂的事情,如果你没有把它搞定,你会搞砸第三方键盘如Swiftkey和Swype.我真的不建议这样做.

如果你想这样做,你最好的机会就是声称你的窗口是一种TYPE_NULL输入类型.大多数键盘都会自行愚蠢,并假设您只接受该模式下最简单的命令.但你不能指望它.

我会看看课程InputConnection返回的内容EditText并尽可能多地复制它.


Sri*_*nth 3

我也面临同样的问题。如果我隐藏编辑文本,edtTxt.getText().toString()则始终为空。所以我一直喜欢

<EditText
    android:id="@+id/edtTxt"
    android:layout_width="0px"
    android:layout_height="0px" />
Run Code Online (Sandbox Code Playgroud)

所以该用户看不到它。点击按钮

edtTxt.requestFocus();
edtTxt.setText("");
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.toggleSoftInputFromWindow(edtTxt.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED,
            0);
Run Code Online (Sandbox Code Playgroud)

现在edtTxt.getText().toString()给出我使用键盘输入的文本。