BottomNavigationViewにバッジをつける

AndroidのBottomNavigationViewにバッジを付ける方法

今回は良さそうな AHBottomNavigation というライブラリを採用した

build.gradleに追加

implementation 'com.aurelhubert:ahbottomnavigation:2.1.0'

layoutはこんな感じ

<com.aurelhubert.ahbottomnavigation.AHBottomNavigation
            android:id="@+id/navigationView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            app:itemIconTint="@drawable/bottom_navigation_item_state"
            app:itemTextColor="@drawable/bottom_navigation_item_state"
            app:labelVisibilityMode="labeled"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

menuはBottomNavigationViewと同じでOK

ナビゲーションのセットアップ

対象のActivityに追加

onCreateとかで良い

AHBottomNavigation navigation = findViewById(R.id.navigation);
mAdapter = new AHBottomNavigationAdapter(this, R.menu.navigation);
mAdapter.setupWithBottomNavigation(navigation);
navigation.setOnTabSelectedListener(mOnTabSelectedListener);

ナビゲーションの実装

private AHBottomNavigation.OnTabSelectedListener mOnTabSelectedListener = new AHBottomNavigation.OnTabSelectedListener() {
    @Override
    public boolean onTabSelected(int position, boolean wasSelected) {
        MenuItem menuItem = navigationAdapter.getMenuItem(position);

        switch (menuItem.getItemId()) {
            case R.id.menu1:
                webView.loadUrl(getResources().getString(R.string.system_url));
                return true;
            case R.id.menu2:
                webView.loadUrl(getResources().getString(R.string.tab_message));
                return true;
            case R.id.menu3:
                webView.loadUrl(getResources().getString(R.string.tab_camera));
                return true;
            case R.id.menu4:
                webView.loadUrl(getResources().getString(R.string.tab_etc));
                return true;
        }
        return false;
    }
};

バッジを付けるメソッド

適当なところで呼んであげる

private void showNotification(int count) {
    int position = navigationAdapter.getPositionByMenuId(R.id.menu2);
    AHBottomNavigation navigation = findViewById(R.id.navigationView);
    navigation.setNotification(count == 0 ? "" : String.valueOf(count), position);
}