如何解决解决触摸Android屏幕的任何部分时隐藏软键盘的解决方案
此代码将帮助您隐藏键盘,使其与edittext以外的地方或仅在您的活动中编写此代码的任何地方都可以隐藏,或者您可以在项目的基本活动中编写。否则它也将键盘隐藏在webview中。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();
if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText &&
!v.getClass().getName().startsWith("android.webkit.")) {
int[] sourceCoordinates = new int[2];
v.getLocationOnScreen(sourceCoordinates);
float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
hideKeyboard(this);
}
}
return super.dispatchTouchEvent(ev);
}
private void hideKeyboard(Activity activity) {
if (activity != null && activity.getwindow() != null) {
activity.getwindow().getDecorView();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(activity.getwindow().getDecorView().getwindowToken(),0);
}
}
}
public static void hideKeyboard(View view) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(view.getwindowToken(),0);
}
}
解决方法
此代码有助于隐藏键盘:
public static void hideSoftKeyboard(Activity activity){
try{
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(),0
);
}catch(Exception e){
e.printStackTrace();
}
}
希望这有效!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。