在底部导航栏的图标顶部显示徽章

时间:2017-03-08 22:10:07

标签: android material-design bottomnavigationview

我在我的应用中实现了底部导航视图,我已经查看了在this等图标上显示徽章的所有位置 我想知道这是否有可能实施。任何帮助表示赞赏。 谢谢。

15 个答案:

答案 0 :(得分:127)

如果你只是想在这里使用股票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>

然后按ID查找TextView并设置文字。 @drawable/notification_badge只是一个圆形的可绘制

答案 1 :(得分:26)

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

此库是底部导航栏的更高级版本。您只需使用此代码段即可在菜单项上设置徽章。

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

您将获得以下结果

enter image description here

答案 2 :(得分:21)

我遇到了同样的问题,我不想使用图书馆。

因此,我创建了一个名为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>

TextView背景(news_bottom_nav_bg):

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

然后我使用以下2种方法创建了一个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");

编辑: 通过建议jatin rana

增加了改进

答案 3 :(得分:9)

根据@ Tinashe的回答,我希望徽章显示如下: enter image description here

代码:

    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" />

和drawable background 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>

答案 4 :(得分:6)

作为@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);

来自my gist

的来源

答案 5 :(得分:4)

一种简单的方法:

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

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

我能够从回收站适配器内部(片段中)更新(或创建我的BottomNavigationView徽章)而没有任何外部库

初始状态: Initial State

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

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;

最终状态:

Final State

与“添加到购物车”按钮侦听器合为一体:

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

答案 6 :(得分:3)

现在使用最新的材料依赖关系来本地添加徽章 将此添加到您的build.gradle

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

在您的布局中添加

<!-- 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.showBadge(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>

答案 7 :(得分:3)

请尝试一次。

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

答案 8 :(得分:3)

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

但是,如果a)紧迫您的时间,并且您正在使用Google素材库BottomNavigationView Bar或b)您想要添加自己的自定义视图标记,那么接受的答案将不适用于{{1} }

您将需要为不同于所接受答案的视图层次编写代码

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

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

答案 9 :(得分:1)

您可以尝试这种方式:

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>

答案 10 :(得分:0)

使用支持库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/();

答案 11 :(得分:0)

您可以使用此库..在导航栏上添加徽章

https://github.com/ahmedewess/Badged-BottomNavigationBar

enter image description here

答案 12 :(得分:0)

徽章现在已由BadgeDrawable添加为AndroidX BottomNavigationView的一部分。 See docs

fun setBadge(count: Int) {
    if (count == 0) {
        bottomNavigationView.removeBadge(R.id.ticketsNavigation)
    } else {
        val badge = bottomNavigationView.showBadge(R.id.ticketsNavigation)
        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>

答案 13 :(得分:0)

查看文档页面: 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)
}

答案 14 :(得分: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);
    }
}