How to display badge for a menuItem of BottomNavig

2020-01-29 01:27发布

I just want to add badge for a menuItem of BottomNavigationView in my app. I'm using BottomNavigationView of Material Components library(version 1.1.0-alpha08) since its the latest version released just 7 days ago from now I didn't found any tutorial for the same, Now because there are changes made in this version of BottomNavigationView's showBadge method we cannot use that method.

I've tried calling getBadge and getOrCreateBadge method over instance of BottomNavigationView.

BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
    if (bottomNavigationView.getBadge(3) == null) {
        audioPlayingCountBadge = bottomNavigationView.getOrCreateBadge(3);
        audioPlayingCountBadge.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    } else {
        audioPlayingCountBadge = bottomNavigationView.getBadge(3);
    }
    audioPlayingCountBadge.setVisible(true);

I'm noob in android development so if anyone can provide solution for this problem in detail that would be very grateful to me.

1条回答
祖国的老花朵
2楼-- · 2020-01-29 01:44
  • First migrate your project to androidX. How to migrate
  • Include dependency in your build.gradle:

implementation 'com.google.android.material:material:version' Get Version

  • Your Base AppLevel theme should use Material Component Theme like:

Your App Level Theme

  <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

Activity code:

int menuItemId = btmNavView.getMenu().getItem(0).getItemId();  //0 menu item index.  
BadgeDrawable badgeDrawable = btmNavView.getOrCreateBadge(menuItemId);
badgeDrawable.setVisible(true);  
badgeDrawable.setNumber(1);   //1 represents badge value.

XML layout:

 <com.google.android.material.bottomnavigation.BottomNavigationView
      style="@style/Widget.Design.BottomNavigationView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:menu="@menu/bottom_nav_menu"/>
查看更多
登录 后发表回答