我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
多亏了这个SO答案,我得出了以下结论,在我的情况下,当滚动浏览ViewPager的片段时,它很好地工作。。。
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
private void showKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
其他回答
在如此的搜索中,我找到了一个适合我的答案
// Show soft-keyboard:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
// Hide soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
首先,您应该从XML文件中添加addandroid:imeOptions字段,并将其值更改为actionUnspecified|actionGo,如下所示
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text_id"
android:layout_width="fill_parent"
android:layout_height="@dimen/edit_text_height"
android:imeOptions="actionUnspecified|actionGo"
/>
然后在java类中添加setOnEditorActionListener并添加InputMethodManager,如下所示
enterOrderNumber.setOnEditorActionListener(新的TextView.OnEditorActionlister(){
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
return true;
}
return false;
}
});
在Kotlin试试这个
private fun hideKeyboard(){
val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}
在Java中尝试
private void hideKeyboard(){
InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
这对我有用。。
EditText editText=(EditText)findViewById(R.id.edittext1);
放在onClick()中的代码行下面
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
这里隐藏键盘,当我们单击按钮时,当我们触摸EditText键盘时,将显示。
(OR)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
只需在特定活动的AndroidManifest中添加以下行。
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan"/>