这可以通过以下步骤完成
1.在导航抽屉菜单中添加“actionViewClass”属性
使用 Navigation Drawer 创建“Helloworld”应用程序后,在项目层次结构视图的“Menu”文件夹下查找文件“activity_main_drawer.xml”(即 youractivityname_drawer.xml)。
识别组项并添加“app:actionViewClass=android.widget.TextView”,如下所示:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_camera"
android:icon="@drawable/ic_menu_camera"
android:title="Import" />
<item
android:id="@+id/nav_gallery"
app:actionViewClass="android.widget.TextView"
android:icon="@drawable/ic_menu_gallery"
android:title="Gallery" />
<item
android:id="@+id/nav_slideshow"
app:actionViewClass="android.widget.TextView"
android:icon="@drawable/ic_menu_slideshow"
android:title="Slideshow" />
<item
android:id="@+id/nav_manage"
android:icon="@drawable/ic_menu_manage"
android:title="Tools" />
</group>
2。声明 Navigation Drawer 菜单项并使用标记值初始化该项。
在您的主 Activity 中,声明 Navigation Drawer 的菜单项,如下所示
//Create these objects above OnCreate()of your main activity
TextView slideshow,gallery;
//These lines should be added in the OnCreate() of your main activity
gallery=(TextView) MenuItemCompat.getActionView(navigationView.getMenu().findItem(R.id.nav_gallery));
slideshow=(TextView) MenuItemCompat.getActionView(navigationView.getMenu().findItem(R.id.nav_slideshow));
//This method will initialize the count value
initializeCountDrawer();
initializeCountDrawer() 可以在任何需要的地方调用。它还可以用于更新导航抽屉菜单项中的计数或徽章值。
private void initializeCountDrawer() {
//Gravity property aligns the text
gallery.setGravity(Gravity.CENTER_VERTICAL);
gallery.setTypeface(null, Typeface.BOLD);
gallery.setTextColor(getResources().getColor(R.color.colorAccent));
gallery.setText("99+");
slideshow.setGravity(Gravity.CENTER_VERTICAL);
slideshow.setTypeface(null,Typeface.BOLD);
slideshow.setTextColor(getResources().getColor(R.color.colorAccent));
//count is added
slideshow.setText("7");
}
添加上述方法后,运行应用程序。瞧!
导航抽屉的“画廊”和“幻灯片”菜单项上将显示一个简单的徽章计数。
动态徽章值
如果您需要动态徽章值,例如从 API 调用或 SQLite 数据库更新值,请创建可重用方法并在 Activity 的 OnStart() 或 OnResume() 方法上更新它。
完整的源代码可以找到here