How to implement a badge counter on android hambur

2019-04-11 05:17发布

问题:

This question already has an answer here:

  • Add new item count to icon on button - Android 5 answers

I am trying to implement a counter badge on the hamburger menu icon (i.e. not the other menu icons). Similar to the eBay app. as in..

Has anyone looked into this? Trying to figure out the cleanest way possible.

回答1:

its pretty simple to do with the Toolbar Widget you could follow below example to achieve that:

first create an Oval shape

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

then create a toolbar widget as below:

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:background="?colorPrimary">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/openMenu"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/ic_menu"/>

        <TextView
            android:id="@+id/badger"
            android:layout_width="16dp"
            android:layout_height="16dp"
            android:layout_gravity="end|right|top"
            android:layout_marginTop="10dp"
            android:background="@drawable/badge"
            android:gravity="center"
            android:text="1"
            android:textColor="@color/white"/>

    </FrameLayout>
</android.support.v7.widget.Toolbar>