4

I've tried adding a simple BadgeDrawable to a MaterialButton but the badge isn't being shown.

I have tried, in my build.gradle the following versions: 'com.google.android.material:material:1.2.0-alpha02' and 'com.google.android.material:material:1.1.0-alpha06' .

Code is more or less:

private void addBadgeFor(MaterialButton button, int count) {
    if (count > 0) {
        final BadgeDrawable badge = BadgeDrawable.create(getContext());
        badge.setNumber(count);
        badge.setBackgroundColor(getActivity().getResources().getColor(R.color.badgeBackground));
        badge.setBadgeTextColor(getActivity().getResources().getColor(R.color.badgeText));
        BadgeUtils.attachBadgeDrawable(badge, button, null);
    }
}

I've tried with/without colors. minSdk is 24, target is 29.

Does anyone know if MaterialButton supports BadgeDrawable?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841

1 Answers1

1

You can use in your layout:

<FrameLayout
    android:id="@+id/layout"
    android:clipChildren="false"
    android:clipToPadding="false">

  <com.google.android.material.button.MaterialButton
      android:id="@+id/button"
      ../>

</FrameLayout>

Then in your code you can apply the BadgeDrawable with:

    MaterialButton button = findViewById(R.id.button);

    button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            BadgeDrawable badgeDrawable = BadgeDrawable.create(MainActivity.this);
            badgeDrawable.setNumber(9);
            
            BadgeUtils.attachBadgeDrawable(badgeDrawable, button, findViewById(R.id.layout));
            button.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841