[英]Android - open soft keyboard and get value without dialog or layout or edittext
Is there a way to just open the soft keyboard, without an actual dialog nor an input field, and get the input value in a string?有没有办法只打开软键盘,没有实际的对话框或输入字段,并在字符串中获取输入值? the keyboard itself already has a "done" button;
键盘本身已经有一个“完成”按钮; can I just: press a button, keyboard opens with its own builtin inputbox, enter value, press "done", get result in a variable.
我可以:按下一个按钮,键盘打开它自己的内置输入框,输入值,按“完成”,得到一个变量的结果。
I would add an editText an make it invisible and put on the focus on it.我会添加一个 editText 使其不可见并将焦点放在它上面。 To show it explicitly:
要明确显示它:
editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
and hide it again并再次隐藏它
InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
I designed a different solution, inspired by Tobias suggestions plus this answer .我设计了一个不同的解决方案,灵感来自 Tobias 的建议和这个答案。 I created an AlertDialog popup with an EditText in it.
我创建了一个 AlertDialog 弹出窗口,其中包含一个 EditText。 Then I added a delayed "touch" into the edittext to open the soft keyboard, then handled the "done" event to get the input value and also close the underlying popup.
然后我在edittext中添加了一个延迟的“触摸”以打开软键盘,然后处理“完成”事件以获取输入值并关闭底层弹出窗口。 Here is some sample code:
下面是一些示例代码:
//Open an AlertDialog popup
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
//create a simple EditText
final EditText input = new EditText(activity);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setImeOptions(EditorInfo.IME_ACTION_DONE);
builder.setView(input);
//touch into the EditText to open the softkeyboard (600ms delay)
new Handler().postDelayed(new Runnable() {
public void run() {
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
}, 600);
alertDialog = builder.show();
AlertDialog finalAlertDialog = alertDialog;
//Handle Keyboard event to get value and close the popup
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId <= EditorInfo.IME_ACTION_PREVIOUS)) {
doOperation();
finalAlertDialog.cancel();
}
return false;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.