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

如何让NavigationView中选中的菜单项不显示为粗体文本?

解决NavigationView选中菜单项默认粗体的问题

在Material Components for Android 1.8.0-alpha03版本中,NavigationView的选中菜单项会默认显示为粗体,你可以通过以下两种方式取消这个效果:

方法一:通过自定义样式(推荐)

这种方式从样式层面统一配置,无需修改代码逻辑:

  1. 在res/values/styles.xml中定义选中菜单项的文本样式,强制使用正常字重:
<style name="NavMenuItemSelectedText" parent="TextAppearance.Material3.BodyLarge">
    <item name="android:textStyle">normal</item>
    <!-- 可选:指定默认字体,保持和未选中项一致 -->
    <item name="fontFamily">@font/your_app_default_font</item>
</style>
  1. 定义NavigationView的自定义样式,引用上述文本样式:
<style name="CustomNavigationView" parent="Widget.Material3.NavigationView">
    <item name="itemTextAppearanceSelected">@style/NavMenuItemSelectedText</item>
</style>
  1. 在布局文件中给NavigationView应用这个自定义样式:
<com.google.android.material.navigation.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    style="@style/CustomNavigationView"
    app:menu="@menu/your_nav_menu" />

方法二:通过代码动态设置

如果需要更灵活的控制,可以在代码中修改选中菜单项的文本样式:

Kotlin示例

val navView = findViewById<NavigationView>(R.id.nav_view)

// 设置选中监听器时重置样式
navView.setNavigationItemSelectedListener { menuItem ->
    // 重置所有菜单项的文本样式为正常
    navView.menu.forEach { item ->
        val normalText = SpannableString(item.title).apply {
            setSpan(StyleSpan(Typeface.NORMAL), 0, length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        }
        item.title = normalText
        item.isChecked = item == menuItem
    }
    // 处理页面跳转等逻辑
    true
}

Java示例

NavigationView navView = findViewById(R.id.nav_view);

navView.setNavigationItemSelectedListener(menuItem -> {
    // 重置所有菜单项样式
    for (int i = 0; i < navView.getMenu().size(); i++) {
        MenuItem item = navView.getMenu().getItem(i);
        SpannableString normalText = new SpannableString(item.getTitle());
        normalText.setSpan(new StyleSpan(Typeface.NORMAL), 0, normalText.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        item.setTitle(normalText);
        item.setChecked(item == menuItem);
    }
    // 处理其他逻辑
    return true;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:30:06