作者:yuyiyin乐悠悠_964 | 来源:互联网 | 2023-05-18 09:48
publicclassKeyboardUtil{***根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏*
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() && event.getY() > top && event.getY() }
// 如果焦点不是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);
}
}
/**
* 关闭键盘
* @param context
*/
public static void closeSoftKeyBoard(Activity context)
{
View view = context.getWindow().peekDecorView();
if (view != null)
{
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* 打开键盘
* @param context
*/
public static void openSoftKeyBoard(Activity context)
{
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}