Android软键盘使用
16lz
2021-12-04
点击其他区域隐藏软键盘
思路:
通过dispatchTouchEvent的ACTION_DOWN事件判断是否点击了非EditText区域,然后进行隐藏。
代码:
@Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (isShouldHideInput(v, ev)) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } return super.dispatchTouchEvent(ev); } // 必不可少,否则所有的组件都不会有TouchEvent了 if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
isShouldHideInput(View v, MotionEvent me)方法:
public boolean isShouldHideInput(View v, MotionEvent event) { if (v != null && (v instanceof EditText)) { int[] leftTop = { 0, 0 }; //获取输入框当前的location位置 v.getLocationInWindow(leftTop); int left = leftTop[0]; int top = leftTop[1]; int bottom = top + v.getHeight(); int right = left + v.getWidth(); if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) { // 点击的是输入框区域,保留点击EditText的事件 return false; } else { return true; } } return false; }
一个软键盘工具类:
public class KeyboardUtils{ public static void showKeyboard(View view){ InputMethodManager imm = (InputMethodManager)view.getSystemService(Context.INPUT_METHOD_SERVICE); if(imm != null){ view.requestFocus(); imm.showSoftInput(view, 0); } } public static void hideKeyboard(View view){ InputMethodManager imm = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if(imm != null){ imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public static void toggleSoftInput(View view){ InputMethodManager imm = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if(imm != null){ imm.toggleSoftInput(0, 0); } }}
更多相关文章
- android 点击返回键退出程序的方法
- Android(安卓)SDK 自带项目GestureBuilderActivity
- android Gallery(画廊)以及BaseAdapter
- Android(安卓)SDK 自带项目GestureBuilderActivity
- windowSoftInputMode属性设置值
- windowSoftInputMode属性设置值
- EditText阻止自动弹出虚拟键盘
- windows下Android开发环境配置
- Android(安卓)弹出键盘向上顶布局