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(); } }