簡體   English   中英

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

[英]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 Design 添加一個編號為 1 的徽章(請參閱文檔)。

這就是我嘗試的方式:

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>

在您的活動中;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM