300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 点击空白区域关闭软键盘

点击空白区域关闭软键盘

时间:2020-12-08 21:14:41

相关推荐

点击空白区域关闭软键盘

很多时候,需求需要点击输入框其他地方,关闭软键盘,下面分享一个utils

public class HideKeyBroadUtils {private HideKeyBroadUtils(){}/*** 隐藏软键盘* @param activity* @param ev*/public static void hide(Activity activity, MotionEvent ev){if (ev.getAction() == MotionEvent.ACTION_DOWN) {View view = activity.getCurrentFocus();if (isHideInput(view, ev)) {HideSoftInput(activity,view.getWindowToken());}}}// 判定是否需要隐藏private static boolean isHideInput(View v, MotionEvent ev) {if (v != null && (v instanceof EditText)) {int[] l = { 0, 0 };v.getLocationInWindow(l);int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left+ v.getWidth();if (ev.getX() > left && ev.getX() < right && ev.getY() > top&& ev.getY() < bottom) {return false;} else {return true;}}return false;}// 隐藏软键盘private static void HideSoftInput(Activity activity,IBinder token) {if (token != null) {InputMethodManager manager = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);manager.hideSoftInputFromWindow(token,InputMethodManager.HIDE_NOT_ALWAYS);}}}

只需重写activity里的dispatchTouchEvent方法,然后调用如下

@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {HideKeyBroadUtils.hide(this,ev);return super.dispatchTouchEvent(ev);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。