I would like to show count badge in front of Floating Action Button in android. I used FrameLayout in order to achieve that. My code is here
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/send_button"
android:layout_toLeftOf="@+id/send_button"
android:layout_toStartOf="@+id/send_button"
android:layout_gravity="end|bottom"
android:id="@+id/frameLayout">
<android.support.design.widget.FloatingActionButton
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/listen_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:backgroundTint="#e3e3e3" />
<TextView
android:id="@+id/textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10"
android:textColor="#FFF"
android:textSize="10sp"
android:textStyle="bold"
android:background="@drawable/badge_circle"
android:layout_gravity="right|bottom"
android:layout_alignBottom="@+id/frameLayout"
android:layout_toLeftOf="@+id/frameLayout"
android:layout_toStartOf="@+id/frameLayout" />
</FrameLayout>
I get the count badge below the FAB, as shown below
I need the count badge to be in front of the FAB.
You can use the BadgeDrawable
provided by the Material Components Library.
Something like:
fab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
BadgeDrawable badgeDrawable = BadgeDrawable.create(MainActivity.this);
badgeDrawable.setNumber(2);
//Important to change the position of the Badge
badgeDrawable.setHorizontalOffset(30);
badgeDrawable.setVerticalOffset(20);
BadgeUtils.attachBadgeDrawable(badgeDrawable, fab, null);
fab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
Currently (1.3.0-alpha02
) there isn't a method to change the radius, but you can override this dimen in your project (dimens.xml
):
<dimen name="mtrl_badge_with_text_radius">12dp</dimen>
I used the CounterFab library to achieve this.
It is as simple as adding it to your XML layout file instead of the regular FloatingActionButton
and calling counterFab.setCount(10);
(See usage example here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With