我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
首先,您应该从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;
}
});
其他回答
只需在BaseActivity和BaseFragment中为整个应用程序创建通用方法
在onCreate()中初始化inputMethodManager
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
使用此方法隐藏和显示键盘
public void hideKeyBoard(View view) {
if (view != null) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void showKeyboard(View view, boolean isForceToShow) {
if (isForceToShow)
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
else if (view != null)
inputMethodManager.showSoftInput(view, 0);
}
在绝望中尝试了所有的方法,结合了所有方法,当然,在Android 4.0.3中键盘不会关闭(它在Honeicomb AFAIR中确实有效)。
然后我突然发现了一个明显获胜的组合:
textField.setRawInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_NORMAL);
结合你平时的食谱
blahblaj.hideSoftInputFromWindow ...
希望这能阻止某人自杀。。我很接近它。当然,我不知道为什么它会起作用。
试试这个
简单,您可以在活动中调用
public static void hideKeyboardwithoutPopulate(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
在您的主活动中调用
hideKeyboardwithoutPopulate(MainActivity.this);
使用这个
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
试试这个
public void disableSoftKeyboard(final EditText v) {
if (Build.VERSION.SDK_INT >= 11) {
v.setRawInputType(InputType.TYPE_CLASS_TEXT);
v.setTextIsSelectable(true);
} else {
v.setRawInputType(InputType.TYPE_NULL);
v.setFocusable(true);
}
}