Material Design 3下导航抽屉文字样式不一致原因咨询

使用Material Design 3开发时,发现NavigationView中部分文本为粗体,部分为常规字体,以下是原因分析及相关代码:
布局代码
<?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activities.MainActivity" tools:openDrawer="start"> ... <com.google.android.material.navigation.NavigationView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/menu_navigation_drawer" /> </androidx.drawerlayout.widget.DrawerLayout>
菜单代码
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="Other"> <menu> <item android:icon="@drawable/ic_star" android:title="Rate the app" /> <item android:icon="@drawable/ic_share" android:title="Share the app" /> <item android:icon="@drawable/ic_shield" android:title="Privacy policy" /> <item android:icon="@drawable/ic_document" android:title="Terms of services" /> </menu> </item> </menu>
原因说明
这是Material Design 3中NavigationView的默认样式行为:
- 菜单里的
Other属于分组标题,按照MD3的设计规范,导航抽屉的分组标题默认使用粗体文本,用来明确划分不同的菜单项区域,提升菜单结构的可读性。 - 嵌套在
<menu>标签下的子项(如Rate the app、Share the app等)是普通可点击菜单项,默认使用常规字体,和粗体标题形成视觉层级差异,让用户能快速区分标题与操作项。
自定义样式方案
如果需要修改默认的字体粗细,可以通过自定义文本外观实现:
- 在
NavigationView中添加属性指定自定义样式:
<com.google.android.material.navigation.NavigationView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/menu_navigation_drawer" app:headerTextAppearance="@style/CustomNavHeaderText" app:itemTextAppearance="@style/CustomNavItemText" />
- 在
styles.xml中定义对应的样式:
<!-- 修改分组标题为常规字体 --> <style name="CustomNavHeaderText" parent="TextAppearance.Material3.HeadlineSmall"> <item name="android:textStyle">normal</item> </style> <!-- 修改普通菜单项为粗体 --> <style name="CustomNavItemText" parent="TextAppearance.Material3.BodyLarge"> <item name="android:textStyle">bold</item> </style>
内容的提问来源于stack exchange,提问作者Taha Sami
相关产品推荐
相关产品推荐

