如何在按钮上方添加徽章?

How to add a badge above a button?

在我的 MainActivity class 中,我有这个按钮:

<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" />

我现在想使用 Material 设计添加编号为 1 的徽章(请参阅 documentation)。

这是我试过的方法:

public void setBadge() {
    BadgeDrawable badgeDrawable =  BadgeDrawable.create(MainActivity.this);
    badgeDrawable.setNumber(1);
    BadgeUtils.attachBadgeDrawable(badgeDrawable, findViewById(R.id.target));
}

但我得到的是错误

'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)'

如果您在小于 18 岁的设备上尝试过此操作 API 这可能有效;

在您的 XML 中用 FrameLayout;

包裹按钮
<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>

在你的 Activity;

//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));
});