Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Badge count on Floating action button

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

enter image description here

I need the count badge to be in front of the FAB.

like image 371
Feras AlTuraigi Avatar asked Jun 05 '16 07:06

Feras AlTuraigi


Video Answer


2 Answers

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

enter image description here

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>

enter image description here

like image 85
Gabriele Mariotti Avatar answered Sep 21 '22 12:09

Gabriele Mariotti


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

like image 32
Tomer Avatar answered Sep 20 '22 12:09

Tomer