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
        }
    }
}); 
    
posted @   yongfengnice  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示