1. 程式人生 > 其它 >android開發獲取鍵盤高度以及判斷鍵盤是否顯示(相容分屏模式)

android開發獲取鍵盤高度以及判斷鍵盤是否顯示(相容分屏模式)

android開發獲取鍵盤高度以及判斷鍵盤是否顯示

//方法一(相容分屏模式):反射獲取鍵盤高度,,,-1表示反射失敗,0表示鍵盤隱藏,大於0表示鍵盤顯示。。。
//關於android 9 之後非公開api呼叫黑名單表格hiddenapi-flags.csv連結:https://developer.android.google.cn/guide/app-compatibility/restrictions-non-sdk-interfaces
public int getKeyboardHeight(Context context){
   try {
      InputMethodManager im = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
      Method method = im.getClass().getDeclaredMethod("getInputMethodWindowVisibleHeight");
      method.setAccessible(true);
      Object height = method.invoke(im);
      return Integer.parseInt(height.toString());
   }catch (Throwable e){
      return -1;
   }
}
//方法二(分屏模式可能失效):新增ViewTreeObserver判斷decorView的高度和contentView的高度,可以大致判斷,不過這種方式在分屏模式可能失效
View contentView = findViewById(R.id.content_view);
contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //contentView.getRootView()即得到的是decorView
        int heightDiff = contentView.getRootView().getHeight() - contentView.getHeight();
        if (heightDiff > 0.25 * contentView.getRootView().getHeight()) { 
           // if more than 25% of the screen, its probably a keyboard is showing...
           // do something here
        }
    }
});