如何解决以编程方式关闭键盘在Android 10上不起作用
我已经在我的API 19真实设备和API 23模拟器上对其进行了测试,并且此方法可以正常工作:
if(activity != null){
View view = activity.getCurrentFocus();
if (view != null){
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if(inputManager != null){
inputManager.hideSoftInputFromWindow(view.getwindowToken(),0);
}
}
}
但是,它不能在我的Pixel 4a(android 10)真实设备上运行。有人知道如何在Android 10上以编程方式关闭键盘吗?
解决方法
尝试以下静态方法
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View currentFocus = activity.getCurrentFocus();
if (inputMethodManager != null) {
IBinder windowToken = activity.getWindow().getDecorView().getRootView().getWindowToken();
inputMethodManager.hideSoftInputFromWindow(windowToken,0);
inputMethodManager.hideSoftInputFromWindow(windowToken,InputMethodManager.HIDE_NOT_ALWAYS);
if (currentFocus != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(),0);
}
}
}
,
根据您所在的位置,可以使用以下方法之一:
boolean hideSuccess = KeyboardUtils.hideKeyboard(activity);
// or
boolean hideSuccess = KeyboardUtils.hideKeyboard(fragment);
// or
boolean hideSuccess = KeyboardUtils.hideKeyboard(editText); // It's recommended
KeyboardUtils.java
import android.app.Activity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import androidx.fragment.app.Fragment;
/**
* @author aminography
*/
public class KeyboardUtils {
public static boolean hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null) {
View focus = activity.getCurrentFocus();
if (focus == null) focus = new View(activity);
return imm.hideSoftInputFromWindow(focus.getWindowToken(),0);
} else {
return false;
}
}
public static boolean hideKeyboard(Fragment fragment) {
InputMethodManager imm = (InputMethodManager) fragment.requireContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null) {
View focus = fragment.requireActivity().getCurrentFocus();
if (focus == null) focus = new View(fragment.requireContext());
return imm.hideSoftInputFromWindow(focus.getWindowToken(),0);
} else {
return false;
}
}
public static boolean hideKeyboard(EditText editText) {
InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null) {
return imm.hideSoftInputFromWindow(editText.getWindowToken(),0);
} else {
return false;
}
}
}
,
在清单上添加任务权限。
<uses-permission android:name="android.permission.GET_TASKS"/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。