首页 > 技术文章 > android开发获取键盘高度以及判断键盘是否显示(兼容分屏模式)

yongfengnice 2021-07-29 21:14 原文

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

推荐阅读