[英]Show software keyboard without EditText
我的目标是在某些事件上显示/隐藏屏幕上的软件键盘并拦截来自该键盘的输入。
我发现可以为某些View
class 后代显示软键盘,但我不需要屏幕上文本编辑小部件的任何视觉表示,只需要通过输入拦截以编程方式显示/隐藏软键盘的能力。
实现这一目标的最佳方法是什么?
即使这个问题大约在一年前被问到,它也没有一个被接受且完全有用的答案,而且由于我自己遇到了同样的问题,我虽然我会分享我的解决方案:
正如 Vikram 指出的那样,这是显示软输入的方式:
InputMethodManager im = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(myView, InputMethodManager.SHOW_FORCED);
但是您还必须在触摸模式下将视图设置为可聚焦和可聚焦:
myView.setFocusable(true);
myView.setFocusableInTouchMode(true);
或在您看来 XML:
android:focusable = "true"
android:focusableInTouchMode = "true"
您可以使用以下命令强制显示软键盘:
InputMethodManager im = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(myView, InputMethodManager.SHOW_FORCED);
并隐藏:
((InputMethodManager) YourActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(findViewById(R.id.YOUR_VIEW).getWindowToken(), 0);
实际上,您always
可以从清单显示软键盘输入。 将此行添加到要显示软键盘的每个活动中:
android:windowSoftInputMode="stateAlwaysVisible"
无论视图中是否没有编辑文本,软键盘都会出现。 例子:
<activity android:name=".ChatActivity"
android:windowSoftInputMode="stateAlwaysVisible">
</activity>
但是如何获取用户输入的输入呢?
您可以使用EditText
作为您的view
参数,但您不必向用户显示它,而是为您的editText
视图创建一个父视图(例如LinearLayout
),并在父视图gone
时创建setVisibility
。 此外,您可以继续使用EditText.addTextChangedListener
获取输入
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone">
<EditText
android:layout_width="100dp"
android:layout_height="20dp"
android:focusable = "true"
android:focusableInTouchMode = "true"
android:id="@+id/edt"/>
</LinearLayout>
我必须结合以前的多个答案才能工作
在活动文件中,我添加了这段代码:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="@+id/edt"
android:layout_width="100dp"
android:layout_height="20dp"
android:focusable="true"
android:focusableInTouchMode="true" />
</LinearLayout>
假设我希望在单击按钮时弹出键盘,我在活动(kotlin)文件中添加了这段代码:
binding.button.setOnClickListener {
binding.edt.requestFocus()
val im: InputMethodManager =
(this@MainActivity).getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
im.showSoftInput(binding.edt, InputMethodManager.SHOW_FORCED)
}
代码仅在我添加以下行后才起作用: binding.edt.requestFocus()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.