97

我已经在我的应用程序中实现了底部导航视图,并且我已经查看了在图标顶部显示徽章的每个位置,我想知道 是否甚至可以实现。任何帮助表示赞赏。谢谢你。

4

15 回答 15

163

如果您只想使用股票BottomNavigationView而没有第三方库,这就是我的做法:

BottomNavigationMenuView bottomNavigationMenuView =
            (BottomNavigationMenuView) navigationView.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(3); 
BottomNavigationItemView itemView = (BottomNavigationItemView) v;

View badge = LayoutInflater.from(this)
            .inflate(R.layout.notification_badge, itemView, true);

然后是布局文件:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <TextView
        android:id="@+id/notifications.badge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp"
        android:background="@drawable/notification_badge"
        android:gravity="center"
        android:padding="3dp"
        android:text="9+"
        android:textColor="@color/white"
        android:textSize="11sp" />
</merge>

然后只需TextView通过 id 查找并设置文本。 @drawable/notification_badge只是一个可绘制的圆形

于 2017-10-05T17:17:47.240 回答
88

现在本地支持添加徽章,使用最新的材料依赖项将其添加到您的 build.gradle

    implementation 'com.google.android.material:material:1.1.0-alpha09'

在你的布局中添加这个

<!-- The rest of your layout here ....-->

  <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:menu="@menu/bottom_nav_menu"
            />

那么你可以

     val navBar  = findViewById<BottomNavigationView>(R.id.bottom_navigation)
     navBar.getOrCreateBadge(R.id.action_add).number = 2

您的 R.id.action_add 将是您要放置徽章的菜单项的 ID。从您提供给 BottomNavigationView 的菜单文件中检查它。

确保您的应用主题位于 Theme.MaterialComponents 中

您可以在样式或清单中检查它。对于这个例子,我的是这个

     <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>
        <item name="android:statusBarColor" tools:targetApi="lollipop">@color/colorPrimary</item>
    </style>
于 2019-05-28T10:54:47.183 回答
60

2020年编辑:

相反,使用BottomNavigation材料组件,它支持在项目上添加徽章和许多其他开箱即用的功能:

https://github.com/material-components/material-components-android/blob/master/docs/components/BottomNavigation.md

老答案:

使用支持库底部导航栏时,在菜单项上显示徽章/通知非常复杂。但是,有一些简单的解决方案可以完成它。如 https://github.com/aurelhubert/ahbottomnavigation

这个库是底部导航栏的更高级版本。您可以简单地使用此代码片段在菜单项上设置徽章。

bottomNavigation.setNotification(notification, bottomNavigation.getItemsCount() - 1);

你会得到以下结果

在此处输入图像描述

于 2017-03-10T08:06:06.307 回答
51

编辑 2:
BottomNavigationView 现在支持原生显示徽章,如此处的文档中所述

bottomNavigation.getOrCreateBadge(menuItemId)


我面临同样的问题,我不想使用图书馆。

所以我创建了一个自定义布局,名为layout_news_badge

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/badge_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <TextView
        android:id="@+id/badge_text_view"
        android:layout_width="19dp"
        android:layout_height="19dp"
        android:textSize="11sp"
        android:textColor="@android:color/white"
        android:background="@drawable/news_bottom_nav_bg"
        android:layout_gravity="top"
        android:layout_marginTop="4dp"
        android:layout_marginStart="16dp"
        android:gravity="center"
        android:padding="2dp"
        tools:text="9+" />
</FrameLayout>

文本视图背景(news_bottom_nav_bg):

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="?attr/colorPrimary" />
</shape>

BottomMenuHelper然后我用这两种方法创建了一个:

public static void showBadge(Context context, BottomNavigationView 
    bottomNavigationView, @IdRes int itemId, String value) {
    removeBadge(bottomNavigationView, itemId);
    BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
    View badge = LayoutInflater.from(context).inflate(R.layout.layout_news_badge, bottomNavigationView, false);
    
    TextView text = badge.findViewById(R.id.badge_text_view);
    text.setText(value);
    itemView.addView(badge);
}

public static void removeBadge(BottomNavigationView bottomNavigationView, @IdRes int itemId) {
    BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
    if (itemView.getChildCount() == 3) {
        itemView.removeViewAt(2);
    }
}

然后当我在我的活动中调用它时:

BottomMenuHelper.showBadge(this, mBottomNavigationView, R.id.action_news, "1");

编辑 1: 通过建议jatin rana添加了改进

于 2018-10-18T16:08:48.057 回答
24

更新:现在材料支持徽章,见下文

材料装袋

底部导航

val badge = bottomNavigation.getOrCreateBadge(menuItemId)
badge.isVisible = true
// An icon only badge will be displayed unless a number is set:
badge.number = 99

旧答案

根据@Tinashe 的回答,我希望徽章显示为无编号的波纹管: 在此处输入图像描述

代码:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
        // position = 2
        addBadge(POSITION_HISTORY)
    }

    /**
     * add badge(notification dot) to bottom bar
     * @param position to get badge container
     */
    @SuppressLint("PrivateResource")
    private fun addBadge(position: Int) {
        // get badge container (parent)
        val bottomMenu = navigation.getChildAt(0) as? BottomNavigationMenuView
        val v = bottomMenu?.getChildAt(position) as? BottomNavigationItemView

        // inflate badge from layout
        badge = LayoutInflater.from(this)
                .inflate(R.layout.badge_layout, bottomMenu, false)

        // create badge layout parameter
        val badgeLayout: FrameLayout.LayoutParams = FrameLayout.LayoutParams(badge?.layoutParams).apply {
            gravity = Gravity.CENTER_HORIZONTAL
            topMargin = resources.getDimension(R.dimen.design_bottom_navigation_margin).toInt()

            // <dimen name="bagde_left_margin">8dp</dimen>
            leftMargin = resources.getDimension(R.dimen.bagde_left_margin).toInt()
        }

        // add view to bottom bar with layout parameter
        v?.addView(badge, badgeLayout)
    }

badge_layout.xml (badge_size=12dp)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/badge_size"       
    android:layout_height="@dimen/badge_size"
    android:background="@drawable/new_notification" />

和可绘制的背景 new_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <corners android:radius="100dp"/>
    <solid android:color="#F44336"/>
</shape>
于 2018-02-11T06:37:31.383 回答
17

BadgeDrawable 现在已将 Badge 添加为 AndroidX BottomNavigationView 的一部分。 查看文档

fun setBadge(count: Int) {
    if (count == 0) {
        bottomNavigationView.removeBadge(R.id.ticketsNavigation)
    } else {
        val badge = bottomNavigationView.getOrCreateBadge(R.id.ticketsNavigation) // previously showBadge
        badge.number = count
        badge.backgroundColor = getColor(R.color.badge)
        badge.badgeTextColor = getColor(R.color.blackTextColor)
    }
}

// Menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/ticketsNavigation"
        android:icon="@drawable/vector_drawable_navbar_tickets"
        android:title="@string/tickets_title"/>
    ...
</menu>

编辑:

如评论中所述,应该可以只更新徽章计数,而无需像这样一直添加或删除徽章:

fun setBadge(count: Int) {
    bottomNavigationView.getBadge(menuItemId)?.isVisible = count > 0
}
于 2019-07-04T11:32:57.103 回答
8

作为@zxbin 的回答。您可以检查BadgeView并尝试以下代码

BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
navigation.setSelectedItemId(R.id.navigation_store);
BottomNavigationMenuView bottomNavigationMenuView =
        (BottomNavigationMenuView) navigation.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(4); // number of menu from left
new QBadgeView(this).bindTarget(v).setBadgeNumber(5);

来自我的要点

于 2017-08-18T07:37:15.587 回答
8

一个简单的方法:

随着 Material Design 更新了他们的库并根据

https://medium.com/over-engineering/hands-on-with-material-components-for-android-bottom-navigation-aae2aa9066be

我能够在没有任何外部 lib的情况下从我的回收器适配器(在片段中)内部更新(或创建我的 BottomNavigationView 徽章) 。

初始状态: 初始状态

所以,就像在适配器中一样,我从我的活动中获得了上下文,我访问它并恢复底部导航的实例:

navBottomView = ((AppCompatActivity)this.context).findViewById(R.id.nav_view);

检查徽章是否为空(尚未创建),如果是,请将其设置为选择的数量:

  BadgeDrawable badgeDrawable = navBottomView.getBadge(R.id.navigation_carrinho);
  if (badgeDrawable == null)
      navBottomView.getOrCreateBadge(R.id.navigation_carrinho).setNumber(item.getQuantidade());

否则获取之前的数量并增加徽章值:

int previousValue = badgeDrawable.getNumber();
badgeDrawable.setNumber(previousValue + item.getQuantidade());

不要忘记导入:

import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationView;

最终状态:

最终状态

多合一与添加到购物车按钮侦听器:

btnAddCarrinho.setOnClickListener(v -> {
            navBottomView = ((AppCompatActivity) this.context).findViewById(R.id.nav_view);
            BadgeDrawable badgeDrawable = navBottomView.getBadge(R.id.navigation_carrinho);
            if (badgeDrawable == null) {
                navBottomView.getOrCreateBadge(R.id.navigation_carrinho).setNumber(item.getQuantidade());
            } else {
                int previousValue = badgeDrawable.getNumber();
                badgeDrawable.setNumber(previousValue + item.getQuantidade());
            }
        });
于 2020-04-06T06:05:12.213 回答
5

请尝试一次。

1)为徽章创建xml文件(例如notification_badge_view.xml)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/badge"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="top|center_horizontal"
        android:layout_marginStart="10dp"
        android:gravity="center"
        android:padding="3dp"
        app:srcCompat="@drawable/notification_badge" />
</FrameLayout>

2)为通知点形状创建可绘制文件(例如badge_circle.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/colorAccent" />
    <stroke
        android:width="2dp"
        android:color="@android:color/white" />
</shape>

3) 在您的活动 onCreate 方法中,将徽章视图添加到BottomNavigationView

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);

         addBadgeView();

    }

4) addBadgeView 方法如下

private void addBadgeView() {
        try {
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationBar.getChildAt(0);
            BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0); //set this to 0, 1, 2, or 3.. accordingly which menu item of the bottom bar you want to show badge
            notificationBadge = LayoutInflater.from(LandingActivity.this).inflate(R.layout.view_notification_badge, menuView, false);
            itemView.addView(notificationBadge);
            notificationBadge.setVisibility(GONE);// initially badge will be invisible 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意:bottomNavigationBar 是您的底栏视图。

5)通过以下方法刷新徽章以显示和隐藏

private void refreshBadgeView() {
        try {
            boolean badgeIsVisible = notificationBadge.getVisibility() != GONE;
            notificationBadge.setVisibility(badgeIsVisible ? GONE : VISIBLE);//makes badge visible and invisible 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

6)当我们点击特定的底栏页面时,通过以下行精细地隐藏。

bottomNavigationBar.setOnNavigationItemSelectedListener(new 
BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) 
              {
                switch (menuItem.getItemId()) {
                    case R.id.bottom_bar_one:
                        //while moving to first fragment
                        notificationBadge.setVisibility(GONE);
                        break;
                    case R.id.bottom_bar_two:
                        //moving to second fragment
                        break;
                    case R.id.bottom_bar_three:
                        //moving to third fragment
                        break;
                }
                return true;
            }
        });
于 2019-08-14T10:39:14.703 回答
3

@Abel 的答案是最好的,除非您已经拥有一组复杂的主题并且没有时间全部更改。

但是,如果 a) 您时间紧迫,并且您正在使用 Google 材料库 BottomNavigationView Bar 或 b) 您想要添加自己的自定义视图徽章 - 那么接受的答案将无法使用com.google.android.material:material:1.1.0

您将需要为与接受的答案不同的视图层次结构编码

  BottomNavigationItemView itemView = (BottomNavigationItemView) ((BottomNavigationMenuView) mBottomNavigation.getChildAt(0)).getChildAt(2);
  View badge = LayoutInflater.from(this).inflate(R.layout.navigation_dot, itemView, false);
  itemView.addView(badge);

如果您确实想更新主题并更新为

com.google.android.material:material:1.1.0-alpha09

那么你需要做的就是

mBottomNavigation.getOrCreateBadge(R.id.navigation_menu_item_one).setNumber(YOUR_NUMBER);

remove 和 number 函数仅存在于 1.1.0-alpha09 版本(及更高版本)中

于 2019-08-15T15:44:33.260 回答
2

你可以这样试试:

BottomNavigationView中放置一个TextView用于计数(BottomNavigationView是一个FrameLayout):

    <android.support.design.widget.BottomNavigationView android:id="@id/bottomMenu" style="@style/bottomMenu">
        <TextView android:id="@id/bottomMenuSelectionsNumber" style="@style/bottomMenuSelectionsNumber"/>
    </android.support.design.widget.BottomNavigationView>

并像这样设计它们:

<style name="bottomMenu">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">@dimen/toolbarHeight</item>
    <item name="android:layout_gravity">center|bottom</item>
    <item name="android:background">@color/colorThird</item>
    <item name="itemBackground">@drawable/tabs_ripple</item>
    <item name="itemIconTint">@drawable/bottom_menu_item_color</item>
    <item name="itemTextColor">@drawable/bottom_menu_item_color</item>
    <item name="menu">@menu/bottom_menu</item>
</style>

<style name="bottomMenuSelectionsNumber">
    <item name="android:text">@string/bottomMenuSelectionsNumber</item>
    <item name="android:textSize">@dimen/appSecondFontSize</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:layout_width">@dimen/bottomMenuSelectionsNumberDim</item>
    <item name="android:layout_height">@dimen/bottomMenuSelectionsNumberDim</item>
    <item name="android:layout_gravity">right|bottom</item>
    <item name="android:layout_marginRight">@dimen/bottomMenuSelectionsNumberMarginR</item>
    <item name="android:layout_marginBottom">@dimen/bottomMenuSelectionsNumberMarginB</item>
    <item name="android:gravity">center</item>
    <item name="android:includeFontPadding">false</item>
    <item name="android:background">@drawable/bottom_menu_selections_number_bg</item>
</style>

bottom_menu_selections_number_bg

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="@color/colorAccent"/>
    <corners android:radius="@dimen/cornerRadius"/>
</shape>
于 2017-10-05T21:36:38.027 回答
2

查看文档页面: https ://material.io/develop/android/components/bottom-navigation-view/

TL;DR: 他们没有更新正确的使用方法,所以他们在文档上留下了一个小错误。要添加或删除徽章,请执行以下操作:

// to remove
bottomNavigationView.removeBadge(R.id.action_settings)

// to add
bottomNavigationView.getOrCreateBadge(R.id.action_settings).apply {
    //if you want to change other attributes, like badge color, add a number, maximum number (a plus sign is added, e.g. 99+)
    number = 100
    maxCharactersCount = 3
    backgroundColor = ContextCompat.getColor(context, R.color.color_red)
}
于 2019-11-21T10:41:36.627 回答
1

使用支持库 BottomNavigationView 很困难。一个简单的解决方案是使用外部组件。一个容易处理的是:https ://github.com/roughike/BottomBar 检查它的文档很简单:

BottomBarTab nearby = bottomBar.getTabWithId(R.id.tab_nearby);
nearby.setBadgeCount(5);

// Remove the badge when you're done with it.
nearby.removeBadge/();
于 2017-08-08T08:46:25.247 回答
1

这是使用材料底部导航创建和删除徽章计数的简单方法。

public class BadgeIconHelper {
    
    public static void showNotificationBadge(BottomNavigationView
                                                     bottomNavigationView, @IdRes int itemId, String value) {
        BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(itemId);
        badge.setBackgroundColor(ContextCompat.getColor(bottomNavigationView.getContext(), R.color.color_primary));
        badge.setBadgeTextColor(ContextCompat.getColor(bottomNavigationView.getContext(), R.color.color_white));
        badge.setMaxCharacterCount(3);
        badge.setVerticalOffset(2);
        badge.setVisible(true);
        badge.setNumber(Integer.parseInt(value));
    }
    
    public static void removeNotificationBadge(BottomNavigationView bottomNavigationView, @IdRes int itemId) {
        BadgeDrawable badgeDrawable = bottomNavigationView.getBadge(itemId);
        if (badgeDrawable != null) {
            badgeDrawable.setVisible(false);
            badgeDrawable.clearNumber();
        }
    }
}
于 2022-01-05T15:49:42.710 回答
0

我以这种方式对@ilbose 做了一些更改答案并测试了大小屏幕尺寸

../drawable/badge_circle.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="@color/solid_red_base" />

和 ../layout/notifcation_badge.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/badge_frame_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="11dp"
android:layout_gravity="center_horizontal">

<TextView
    android:id="@+id/badge_text_view"
    android:layout_width="12dp"
    android:layout_height="12dp"
    android:textSize="11sp"
    android:textColor="@android:color/white"
    android:background="@drawable/message_badge"
    android:layout_gravity="top"
    android:layout_centerHorizontal="true"
    android:padding="2dp"/> </RelativeLayout>

在java代码中

 public static void showBadge(Context context, BottomNavigationView
        bottomNavigationView, @IdRes int itemId, String value) {
    BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
    View badge = LayoutInflater.from(context).inflate(R.layout.message_notification_badge, bottomNavigationView, false);

    TextView text = badge.findViewById(R.id.badge_text_view);
    text.setText(value);
    itemView.addView(badge);
}

 public static void removeBadge(BottomNavigationView bottomNavigationView, @IdRes int itemId) {
    BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
    if (itemView.getChildCount() == 4) {
        itemView.removeViewAt(4);
    }
}
于 2019-12-09T04:14:52.677 回答