Search code examples
androidmaterial-components-androidmaterial-componentsandroid-chips

I need to show a badge on Material chip at the right top. How can I easily do it?


Im trying this way

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        val viewWidth = width.toFloat()
        val padding = chipEndPadding
        canvas.drawOval(viewWidth - padding, padding, viewWidth, padding + padding, paint)
    }

But it doesnt seem to be showing up probably because of the chipDrawable. Any way to accomplish this. This method works for all other views, But Not chip!


Solution

  • You can use the BadgeDrawable provided by the Material Components Library.

    In your layout:

        <com.google.android.material.chip.Chip
            android:id="@+id/chip"
    

    Then:

        chip.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                BadgeDrawable badgeDrawable = BadgeDrawable.create(MainActivity.this);
                badgeDrawable.setNumber(4);
                badgeDrawable.setVerticalOffset(25);
                badgeDrawable.setHorizontalOffset(15);
                BadgeUtils.attachBadgeDrawable(badgeDrawable, chip, null);
    
                chip.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    

    enter image description here