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

Android API35+ Edge-to-edge模式Toolbar适配问题(菜单隐藏时高度异常)

Android API 35+ Edge-to-edge Toolbar 菜单项对齐及高度异常问题解决

在API 35+中系统强制启用Edge-to-edge行为,我尝试给应用Toolbar适配该模式,当前实现代码如下,但出现菜单项未对齐,且隐藏菜单按钮时高度异常的问题:

当前布局代码

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?android:attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp" />

当前代码逻辑

final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
toolbar.showOverflowMenu();
setSupportActionBar(toolbar);

toolbar.setElevation(0);
toolbar.setTitle(ctx.getString(R.string.summary));

// ...其他代码

ViewCompat.setOnApplyWindowInsetsListener(toolbar, (v, windowInsets) -> {
        final Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
        v.setPadding(paddingLeft + insets.left, paddingTop + insets.top, paddingRight + insets.right, paddingBottom);
        
        // return WindowInsetsCompat.CONSUMED;
        return ViewCompat.onApplyWindowInsets(v, windowInsets);
    });

问题图示

  • 截图1:菜单项未对齐效果
    菜单项未对齐
  • 截图2:隐藏菜单按钮后的高度异常效果
    隐藏菜单按钮后高度异常

解决方案

1. 改用系统自动Insets处理,避免手动叠加padding

直接给Toolbar设置padding会破坏内部控件布局计算,建议在布局中添加fitsSystemWindows属性,让系统自动适配Insets:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?android:attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:fitsSystemWindows="true" />

2. 正确处理WindowInsets,避免重复计算

如果需要自定义Insets逻辑,不要叠加原有padding,直接替换为Insets值,并消费Insets防止重复处理:

ViewCompat.setOnApplyWindowInsetsListener(toolbar, (v, windowInsets) -> {
    Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
    v.setPadding(insets.left, insets.top, insets.right, insets.bottom);
    return WindowInsetsCompat.CONSUMED;
});

3. 规范Toolbar高度与标题设置

调用setSupportActionBar(toolbar)后,优先通过ActionBar API设置标题,避免直接操作Toolbar导致布局冲突:

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.setTitle(ctx.getString(R.string.summary));
}

4. 全局启用Edge-to-edge模式

在Activity初始化时先开启全局Edge-to-edge配置,让系统统一处理窗口布局:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
    setContentView(R.layout.activity_main);
    
    // 后续Toolbar初始化代码...
}

以上调整后,Toolbar内部菜单项会自动对齐,高度也会保持正常,同时适配API 35+的Edge-to-edge强制要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:47:18