我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
您也可以使用此代码段在Kotlin中隐藏键盘。
fun hideKeyboard(activity: Activity?) {
val inputManager: InputMethodManager? =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as?
InputMethodManager
// check if no view has focus:
val v = activity?.currentFocus ?: return
inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
}
其他回答
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
在调用onTouchListener之后:
findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Utils.hideSoftKeyboard(activity);
return false;
}
});
简短的回答
在OnClick监听器中,使用IME_ACTION_DONE调用EditText的onEditorAction
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
someEditText.onEditorAction(EditorInfo.IME_ACTION_DONE)
}
});
向下钻取
我觉得这种方法更好,更简单,更符合Android的设计模式。在上面的简单示例中(通常在大多数常见情况下),您将拥有一个具有焦点的EditText,并且它通常也是首先调用键盘的一个(在许多常见情况下它肯定能够调用它)。以同样的方式,它应该是释放键盘的人,通常这可以通过ImeAction来完成。只要看看带有android:imeOptions=“actionDone”的EditText的行为,您就可以通过相同的方式实现相同的行为。
检查此相关答案
我有一个例子,我的EditText也可以位于AlertDialog中,所以键盘应该在关闭时关闭。以下代码似乎在任何地方都有效:
public static void hideKeyboard( Activity activity ) {
InputMethodManager imm = (InputMethodManager)activity.getSystemService( Context.INPUT_METHOD_SERVICE );
View f = activity.getCurrentFocus();
if( null != f && null != f.getWindowToken() && EditText.class.isAssignableFrom( f.getClass() ) )
imm.hideSoftInputFromWindow( f.getWindowToken(), 0 );
else
activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
}
有时,您可能有一个活动包含包含editText的行的列表视图,因此您必须在清单SOFT_INPUT_ADJUST_PAN中进行设置,然后出现键盘,这很烦人。
如果您将以下工作错误放置在onCreate的末尾,则它会起作用
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
},100);
添加到Manifest文件中的活动android:windowSoftInputMode=“stateHidden”。例子:
<activity
android:name=".ui.activity.MainActivity"
android:label="@string/mainactivity"
android:windowSoftInputMode="stateHidden"/>