How to create BadgeDrawable in Android

In this android programming source code example, we are going to create BadgeDrawable in Android

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to create BadgeDrawable in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    android:background="#CACACA">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BadgeDrawable"
        android:textSize="16sp"
        android:layout_centerInParent="true"
        android:textColor="@color/colorPrimary"/>
</RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;


public class AndroidChipActivity19 extends AppCompatActivity {

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.badge_option, menu);
        MenuItem itemUser = menu.findItem(R.id.action_user);
        LayerDrawable icon = (LayerDrawable) itemUser.getIcon();
        setBadgeCount(this, icon, "9");
        return super.onCreateOptionsMenu(menu);
    }

    public void setBadgeCount(Context context, LayerDrawable icon, String count) {
        BadgeDrawable badge;
        // Reuse drawable if possible
        Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
        if (reuse != null && reuse instanceof BadgeDrawable) {
            badge = (BadgeDrawable) reuse;
        } else {
            badge = new BadgeDrawable(context);
        }
        badge.setCount(count);
        icon.mutate();
        icon.setDrawableByLayerId(R.id.ic_badge, badge);
    }

    public class BadgeDrawable extends Drawable {
        private Paint mBadgePaint;
        private Paint mBadgePaint1;
        private Paint mTextPaint;
        private Rect mTxtRect = new Rect();
        private String mCount = "";
        private boolean mWillDraw;

        public BadgeDrawable(Context context) {
            float mTextSize = 16;

            mBadgePaint = new Paint();
            mBadgePaint.setColor(Color.RED);
            mBadgePaint.setAntiAlias(true);
            mBadgePaint.setStyle(Paint.Style.FILL);
            mBadgePaint1 = new Paint();
            mBadgePaint1.setColor(ContextCompat.getColor(context.getApplicationContext(), R.color.colorPrimary));
            mBadgePaint1.setAntiAlias(true);
            mBadgePaint1.setStyle(Paint.Style.FILL);

            mTextPaint = new Paint();
            mTextPaint.setColor(Color.WHITE);
            mTextPaint.setTypeface(Typeface.DEFAULT);
            mTextPaint.setTextSize(mTextSize);
            mTextPaint.setAntiAlias(true);
            mTextPaint.setTextAlign(Paint.Align.CENTER);
        }

        @Override
        public void draw(Canvas canvas) {
            if (!mWillDraw) {
                return;
            }
            Rect bounds = getBounds();
            float width = bounds.right - bounds.left;
            float height = bounds.bottom - bounds.top;
            // Position the badge in the top-right quadrant of the icon.
            /*Using Math.max rather than Math.min */
            float radius = ((Math.max(width, height) / 2)) / 2;
            float centerX = (width - radius - 1) +5;
            float centerY = radius -5;
            if(mCount.length() <= 2){
                // Draw badge circle.
                canvas.drawCircle(centerX, centerY, (int)(radius+7.5), mBadgePaint1);
                canvas.drawCircle(centerX, centerY, (int)(radius+5.5), mBadgePaint);
            }
            else{
                canvas.drawCircle(centerX, centerY, (int)(radius+8.5), mBadgePaint1);
                canvas.drawCircle(centerX, centerY, (int)(radius+6.5), mBadgePaint);
//	        	canvas.drawRoundRect(radius, radius, radius, radius, 10, 10, mBadgePaint);
            }
            // Draw badge count text inside the circle.
            mTextPaint.getTextBounds(mCount, 0, mCount.length(), mTxtRect);
            float textHeight = mTxtRect.bottom - mTxtRect.top;
            float textY = centerY + (textHeight / 2f);
            if(mCount.length() > 2)
                canvas.drawText("99+", centerX, textY, mTextPaint);
            else
                canvas.drawText(mCount, centerX, textY, mTextPaint);
        }

        /*
        Sets the count (i.e notifications) to display.
         */
        public void setCount(String count) {
            mCount = count;
            // Only draw a badge if there are notifications.
            mWillDraw = !count.equalsIgnoreCase("0");
            invalidateSelf();
        }

        @Override
        public void setAlpha(int alpha) {
            // do nothing
        }

        @Override
        public void setColorFilter(ColorFilter cf) {
            // do nothing
        }

        @Override
        public int getOpacity() {
            return PixelFormat.UNKNOWN;
        }
    }
}

menu/badge_option.xml

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

    <item
        android:id="@+id/action_user"
        android:icon="@drawable/badge"
        android:title="@string/user"
        app:showAsAction="always" />
</menu>

drawable/badge.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/ic_user"
        android:gravity="center" />

    <!-- set a place holder Drawable so android:drawable isn't null -->
    <item
        android:id="@+id/ic_badge"
        android:drawable="@drawable/ic_user" />
</layer-list>

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment