In my MainActivity class, I have this button:
JavaScript
x
<Button
android:id="@+id/target"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/speak"
android:layout_marginTop="20dp"
android:background="@drawable/button_red"
android:text="@string/target" />
I now want to add a badge with the number 1, using Material Design (see the documentation).
This is how I tried:
JavaScript
public void setBadge() {
BadgeDrawable badgeDrawable = BadgeDrawable.create(MainActivity.this);
badgeDrawable.setNumber(1);
BadgeUtils.attachBadgeDrawable(badgeDrawable, findViewById(R.id.target));
}
but what I get is the error
‘attachBadgeDrawable(com.google.android.material.badge.BadgeDrawable, android.view.View, android.widget.FrameLayout)’ in ‘com.google.android.material.badge.BadgeUtils’ cannot be applied to ‘(com.google.android.material.badge.BadgeDrawable, android.view.View)’
Advertisement
Answer
If you tried this on a device with <18 API this might work;
In your XML wrap the button with a FrameLayout
;
JavaScript
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="HELLO"/>
</FrameLayout>
In your Activity;
JavaScript
//I've used post to eliminate race condition between the button and its badge.
button.post(() -> {
BadgeDrawable badgeDrawable = BadgeDrawable.create(MainActivity.this);
badgeDrawable.setNumber(1);
//Note that there is a third argument which is our FrameLayout
BadgeUtils.attachBadgeDrawable(badgeDrawable, findViewById(R.id.button), findViewById(R.id.frame));
});