Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

android - How to display badge for a menuItem of BottomNavigationView of material library (version 1.1.0-alpha08)?

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);

If anyone can provide solution for this problem in detail that would be very grateful to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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:

val menuItemId: Int = btm_nav.menu.getItem(0).itemId //0 menu item index.
badgeDrawable = btm_nav.getOrCreateBadge(menuItemId)
badgeDrawable.isVisible = true
badgeDrawable.number = 10

badgeDrawable.badgeGravity = BadgeDrawable.TOP_END    //badge gravity
//BadgeDrawable.TOP_START
//BadgeDrawable.BOTTOM_END
//BadgeDrawable.BOTTOM_START

badgeDrawable.isVisible = false   //hide badge
badgeDrawable.clearNumber()

XML layout:

 <com.google.android.material.bottomnavigation.BottomNavigationView
      android:id="@+id/btm_nav"
      style="@style/Widget.Design.BottomNavigationView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:menu="@menu/bottom_nav_menu"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...