You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:无需开启Edge-to-Edge布局,如何获取左右返回手势区域宽度?

解决方案

不用开启Edge-to-Edge布局,有两种可靠的方法可以获取系统左右返回手势的区域宽度:

方法一:读取系统内置资源值

Android 10及以上的系统,默认定义了侧边返回手势的宽度资源,我们可以通过资源标识符直接读取,无需修改窗口布局状态:

fun getSystemGestureSideWidth(context: Context): Int {
    // 获取系统内置的手势宽度资源ID
    val resId = context.resources.getIdentifier(
        "config_navBarEdgeGestureWidth",
        "dimen",
        "android"
    )
    return if (resId > 0) {
        // 读取系统定义的宽度(像素值)
        context.resources.getDimensionPixelSize(resId)
    } else {
        // 系统未定义时,用48dp作为默认值(覆盖绝大多数设备)
        TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            48f,
            context.resources.displayMetrics
        ).toInt()
    }
}

这个方法的优势是简单直接,不需要依赖窗口Insets的回调,但部分定制ROM可能修改了这个资源值,建议结合第二种方法兜底。

方法二:直接获取当前窗口的WindowInsets

即使保持默认的WindowCompat.setDecorFitsSystemWindows(window, true)(不开启Edge-to-Edge),也可以在窗口加载完成后直接获取WindowInsets,从中提取系统手势区域的宽度:

override fun onWindowFocusChanged(hasFocus: Boolean) {
    super.onWindowFocusChanged(hasFocus)
    if (hasFocus) {
        // 确保窗口已经加载完成,获取当前的WindowInsets
        window.decorView.rootWindowInsets?.let { rootInsets ->
            val windowInsets = WindowInsetsCompat.toWindowInsetsCompat(rootInsets)
            val gestureInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemGestures())
            val leftGestureWidth = gestureInsets.left
            val rightGestureWidth = gestureInsets.right
            // 这里拿到宽度后,就可以调整你的滑动逻辑了
        }
    }
}

注意:必须在窗口获取焦点(比如onWindowFocusChanged)或者View布局完成后(比如view.post { ... })调用,否则rootWindowInsets可能为null。

额外建议

拿到手势宽度后,你可以在自己的滑动事件处理逻辑里做判断:如果用户的触摸起点落在系统手势区域内(左侧0到leftGestureWidth,或右侧屏幕宽度-rightGestureWidth到屏幕宽度),就不触发应用内的滑动操作,让系统处理返回手势;反之则正常响应应用内的滑动。

内容的提问来源于stack exchange,提问作者DewiW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:40:27