1. 监听软键盘
由于官方没有提供相关的监听,只能通过界面布局来判断软键盘显示和隐藏。
通过OnLayoutChangeListener
来监听
getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {@Overridepublic void onLayoutChange(View v, int left, int top, int right, int bottom,int oldLeft, int oldTop, int oldRight, int oldBottom) {}});
通过OnGlobalLayoutListener
来监听
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {}});
判断软键盘显示和隐藏。
private boolean isShowing() {// 获取当前屏幕内容的高度int screenHeight = getWindow().getDecorView().getHeight();// 获取View可见区域的bottomRect rect = new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);return screenHeight > rect.bottom;}
不过在某些导航栏存在的手机上会发生某些问题,可以通过获取导航栏高度来避免。
private int getNavigatorBarHeight() {int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");int height = getResources().getDimensionPixelSize(resourceId);LogTool.logi("SoftManagerListenerActivity", "Status Bar Height = " + height);return height;}
2. 软键盘显示
软键盘显示时可能会覆盖某些控件,必要时需要移动界面。
private void onLayout() {//获取当前屏幕内容的高度int screenHeight = getWindow().getDecorView().getHeight();//获取View可见区域的bottomRect rect = new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);if (screenHeight - getNavigatorBarHeight() > rect.bottom) {// 获取按钮的左上角,按钮高度为40dpint[] location = new int[2];mBtnNext.getLocationOnScreen(location);int bottom = location[1] + getResources().getDimensionPixelSize(R.dimen.margin_dpi_50);// 如果按钮被覆盖,移动整个界面向上移动if (bottom > rect.bottom) {getWindow().getDecorView().scrollBy(0, bottom - rect.bottom);mTranslate = true;}} else {if (mTranslate) {getWindow().getDecorView().scrollTo(0, 0);mTranslate = false;}}}
效果如下
3. 手动显示和隐藏键盘
有些手机在进入界面时不能自动弹出键盘,为确保体验体验,可以代码中弹出。调用postDelayed
方法,是为确保activity
创建完毕。
EditText editText = findViewById(R.id.edit_text);InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);editText.postDelayed(new Runnable() {@Overridepublic void run() {manager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);}}, 300);
隐藏键盘
manager.hideSoftInputFromInputMethod(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
源码下载: /nai-chen/AndroidBlog
参考资料:/shelly-li/p/5639833.html
参考资料:/sinat_31311947/article/details/53914000
相关文章
Android TextView控件
Android Span应用
Android EditText控件
Android 监听软键盘显示和隐藏