Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material circular button in Android?

Take a look at this list item in the CyanogenMod Music app:

enter image description here

Which View is being used for that settings button? It couldn't be an ImageButton because when I press it, it creates a circular ripple:

enter image description here

Perhaps one way to do this is inflating a menu button in Toolbar inside the list. But calling inflateMenu() requires minimum API level 21. What other ways can be used to achieve this? Thank you!

like image 989
Hendra Anggrian Avatar asked Dec 07 '15 11:12

Hendra Anggrian


1 Answers

If you want to have a circular ripple you can define it in two ways.

  1. You can use an unbounded ripple - If you don't define a shape or mask the ripple defaults to a circular shape
  2. You can specifically define the shape of the mask as circular

An unbounded ripple is defined very simply like this:

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/darker_gray" />

If you touch the View it will create basic circular ripple which for example is used on the default Android lock screen when you enter a PIN.


However unbounded ripples by definition don't have any defined bounds and as such are not always what you want. If you just want to specifically define the shape and size of the ripple you can use a mask. This has the advantage that the item used to define the shape will not be drawn. It works like this:

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/darker_gray">

    <!-- If you give an item this mask id then it will only be used to determine the shape of -->
    <!-- ripple, but will not be drawn in any way -->
    <item android:id="@android:id/mask">
        <!-- android:shape defines the shape of the ripple. I use oval for a circular one, -->
        <!-- but there are also rectangle, line, ring -->
        <shape android:shape="oval">
            <solid android:color="@android:color/white"/>
        </shape>
    </item>
</ripple>

You can choose from those two options above - which ever one you like best. Just assign the ripple to an ImageView like this and it should look pretty much like the image in your question:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple"
    android:src="@drawable/your_icon"
    android:clickable="true" />

I added the clickable attribute above so the ripple will be enabled even if you don't assign a click listener to the ImageView. As long as you assign a click listener you don't really need it.

like image 182
Xaver Kapeller Avatar answered Nov 17 '22 11:11

Xaver Kapeller