1.判断不可见区域大高度
private fun isSoftShowing() :Boolean{ //获取当前屏幕内容的高度 val screenHeight = getWindow().getDecorView().getHeight() //获取View可见区域的bottom val rect = Rect(); //DecorView即为activity的顶级view getWindow().getDecorView().getWindowVisibleDisplayFrame(rect) //考虑到虚拟导航栏的情况(虚拟导航栏情况下:screenHeight = rect.bottom + 虚拟导航栏高度) //选取screenHeight*2/3进行判断 return screenHeight*2/3 > rect.bottom }
2.根据参数v来获取
private fun isSHowKeyboard(context: Context, v: View):Boolean { var imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (imm.hideSoftInputFromWindow(v.getWindowToken(), 0)) { imm.showSoftInput(v, 0) return true } else { return false } }
3.重写View的onSizeChanged方法
public class ResizeLayout extends RelativeLayout { // 定义默认的软键盘最小高度,这是为了避免onSizeChanged在某些下特殊情况下出现的问题 private final int SOFTKEYPAD_MIN_HEIGHT = 2 * 48; private OnInputSoftListener onInputSoftListener; public ResizeLayout(Context context) { super(context); } public ResizeLayout(Context context, AttributeSet attrs) { super(context, attrs); } public void setInputSoftListener(OnInputSoftListener listener) { onInputSoftListener = listener; } @Override protected void onSizeChanged(int w, final int h, int oldw, final int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (onInputSoftListener == null || oldw == 0 || oldh == 0) { return; } post(() -> { if (oldh - h > SOFTKEYPAD_MIN_HEIGHT) { onInputSoftListener.onSoftInputShow(); } else if (h - oldh > SOFTKEYPAD_MIN_HEIGHT) { onInputSoftListener.onSoftInputHide(); } }); } /** * 软键盘弹出时回调函数 */ public interface OnInputSoftListener { // 软键盘显示的回调方法 void onSoftInputShow(); // 软键盘隐藏时的回调方法 void onSoftInputHide(); } }