我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
以下是使用Kotlin隐藏软键盘的最简单方法:
//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
if ( currentFocus != null ) {
val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
}
return super.dispatchTouchEvent( ev )
}
其他回答
试试这个
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);
}
}
只需在特定活动的AndroidManifest中添加以下行。
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan"/>
记下所有这些答案,简单地说,我写了一个常用的方法:
/**
* hide soft keyboard in a activity
* @param activity
*/
public static void hideKeyboard (Activity activity){
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if (activity.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
与Android 10(API 29)一起工作
val activityView = activity?.window?.decorView?.rootView
activityView?.let {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(it.windowToken, 0)
}
简单编码:在onCreate()中使用此代码
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);