Unity使用AndroidX获取,导航栏与虚拟键盘的高度

如何在Unity 中使用AndroidX ,参看之前的文章:Unity使用AndroidX

首先,要获取当前的View

cs 复制代码
        AndroidHelper.activity  = UnityPlayer.currentActivity;
        AndroidHelper.window    = activity.getWindow();
        AndroidHelper.decorView = window.getDecorView();

其次,使用setOnApplyWindowInsetsListener监听高度变化。

cs 复制代码
AndroidHelper.activity.runOnUiThread(() -> {
    ViewCompat.setOnApplyWindowInsetsListener(AndroidHelper.decorView, (view, insets) -> {
        AndroidHelper.navigationBarHeight = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom;
        AndroidHelper.keyboardHeight      = insets.getInsets(WindowInsetsCompat.Type.ime())           .bottom;
        AndroidHelper.isKeyboardVisible   = insets.isVisible(WindowInsetsCompat.Type.ime());
        return insets;
    });            
}); 

最后,是导出给Unity调用。

cs 复制代码
// In Unity, it's called with a float return value
public static float getNavigationBarHeight() {
    /*
    var insets = ViewCompat.getRootWindowInsets(AndroidHelper.decorView);

    if (insets != null) {
        return insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom;
    }

    return 0;
    */

    return AndroidHelper.navigationBarHeight;
}


// In Unity, it's called with a float return value
public static float getKeyboardHeight() {
    /*
    var insets = ViewCompat.getRootWindowInsets(AndroidHelper.decorView);

    if (insets != null) {
        return insets.getInsets(WindowInsetsCompat.Type.ime()).bottom;
    }

    return 0;
    */

    return AndroidHelper.keyboardHeight;
}       

注释的部分------是不使用高度监听 ,直接获取高度的方式。

值得指出的是,insets.isVisible(WindowInsetsCompat.Type.ime())------可以准确获得虚拟键盘的可见性,但会有一些延迟(大约0.15秒),可能是弹出动画的时间。

而在手动关闭键盘 的时候(使用键盘上右侧的向下箭头关闭按钮),Unity 会无法正确获取键盘的关闭状态,即已经收起了却还是可见激活状态。这在小窗口悬浮键盘 的时候,就无法通过键盘的高度变化 来判断是否关闭了(从弹出高度到0)------因为在这两种情况下,键盘高度始终返回0(不占用当前View的空间)。

相关推荐
玖玥拾5 小时前
Lua 基础语法(二)
开发语言·unity·lua
玖玥拾10 小时前
Lua 基础语法(三) 元表 metatable、元方法、模拟面向对象
开发语言·unity·lua
谢斯2 天前
[unity]如何在unity中添加newtonsoft-json
unity·json·游戏引擎
天人合一peng2 天前
Unity标记固定颜色及投影标记
unity
云雨巫山2 天前
Unity 游戏开发性能优化全景手册
unity·智能手机·性能优化·游戏引擎
maybeyaluokenai2 天前
unity build in渲染管线概述
unity·图形渲染
云雨巫山2 天前
Unity 性能优化 · 图解全景手册
unity·性能优化·游戏引擎
Madokaly3 天前
DOTween的Vector3Plugin
unity
一梭键盘任平生4 天前
Shader入门笔记2
unity
点心的游戏开发世界4 天前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#