KeyboardUtil:软键盘显示隐藏工具类
程序员文章站
2022-04-21 17:56:00
...
一个控制软键盘显示隐藏的工具类(●’◡’●)
public class KeyboardUtil {
/**
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
*
* @param v
* @param event
* @return
*/
public static boolean isShouldHideKeyboard(View v, MotionEvent event) {
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();
return !(event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom);
}
// 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点
return false;
}
/**
* 获取InputMethodManager,隐藏软键盘
*
* @param token
*/
public static void hideKeyboard(Activity context, IBinder token) {
if (token != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(token,0);
}
}
/**
* 获取InputMethodManager,隐藏软键盘
*
* @param token
*/
public static void hideKeyboard(Activity context, IBinder token,int flags) {
if (token != null) {
InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public static void showKeyBoard(Activity activity, View view){
if(activity != null && view != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
}