Android 安卓-反压关闭软键盘和活动
我有一个活动只为SearchView,这是集中在创建,使软键盘弹出 这是代码(kotlin): 如您所见,我尝试在按下后退按钮时关闭活动,但它仅关闭软键盘 我该怎么做Android 安卓-反压关闭软键盘和活动,android,android-softkeyboard,Android,Android Softkeyboard,我有一个活动只为SearchView,这是集中在创建,使软键盘弹出 这是代码(kotlin): 如您所见,我尝试在按下后退按钮时关闭活动,但它仅关闭软键盘 我该怎么做 提前感谢我建议您尝试使用InputMethodManager隐藏键盘,然后关闭活动。例如,添加kotlin扩展,如下所示 fun View.hideKeyboard() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMe
提前感谢我建议您尝试使用
InputMethodManager
隐藏键盘,然后关闭活动。例如,添加kotlin扩展,如下所示
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
然后在活动backpress方法中调用hideKeyboard
方法
override fun onBackPressed() {
searchInput.hideKeyboard()
finish()
}
您可以创建自定义视图并实现
onKeyPreIme(keyCode:Int,event:KeyEvent)
并检查keyCode==KeyEvent.keyCode\u BACK
事件
希望答案能进一步向您解释
编辑:
尝试为您的搜索视图实现这些功能:
searchInput.setOnQueryTextFocusChangeListener{ _, b->
if(!b){
searchview.isIconified = true
finish()
}
}
使用此静态方法关闭键盘
//to hide keyboard
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
此方法位于JAVA
希望这会有帮助 这回答了你的问题吗?Nop不起作用答案是基于edittext的,与searchview不起作用:/@Pikaboo我已经更新了我的答案。你可以试试新方法。
//to hide keyboard
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}