/ kyokomi note / blog

BottomNavigationのバッチ表示

August 30, 2020 [Android]

BottomNavigationでバッチ表示するのどうやるんだろう?とふと思ってMaterialDesignのガイドラインみてたらなんか簡単に追加できそうだったのでやってみた。

数行のコード書くだけで、こんな感じにできる。

image-20200830164713242

参考

https://material.io/develop/android/components/bottom-navigation

手順

依存はnavitationとmaterialが必要

// app/build.gradle

...

dependencies {
	...
	
	implementation "androidx.navigation:navigation-fragment-ktx:2.3.0"
	implementation "androidx.navigation:navigation-ui-ktx:2.3.0"
	implementation 'com.google.android.material:material:1.3.0-alpha02'
	
	...
}

ActivityでBottomNavigationにbadgeをつける

// MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
	super.onCreate(savedInstanceState)
	setContentView(R.layout.activity_main)
	val navView: BottomNavigationView = findViewById(R.id.nav_view)
	
	// これで100のバッチがつく
	val badge = navView.getOrCreateBadge(R.id.navigation_home)
	badge.number = 100
}

...

テーマをMaterialComponentsのどれかに変更する

// style.xml

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

...

そうしないとエラーになります。

Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:243)
        at com.google.android.material.internal.ThemeEnforcement.checkMaterialTheme(ThemeEnforcement.java:217)
        at com.google.android.material.badge.BadgeDrawable.<init>(BadgeDrawable.java:383)
        at com.google.android.material.badge.BadgeDrawable.createFromAttributes(BadgeDrawable.java:309)
        at com.google.android.material.badge.BadgeDrawable.create(BadgeDrawable.java:277)
        at com.google.android.material.bottomnavigation.BottomNavigationMenuView.getOrCreateBadge(BottomNavigationMenuView.java:664)
        at com.google.android.material.bottomnavigation.BottomNavigationView.getOrCreateBadge(BottomNavigationView.java:683)
last modified September 26, 2020

👋 Related posts in the Android series...