Create icon button - Android

2019-06-19 11:11发布

问题:

I want to create a small icon button as it is described in this chapter of the material guideline, but I can't find any explanation on how to do that.

Here is the button I want to transform to an icon toggle:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_row="4"
    android:layout_column="0"
    android:id="@+id/btn_delete"
    android:drawableStart="@drawable/ic_delete"
    android:drawableLeft="@drawable/ic_delete"
    style="?android:attr/borderlessButtonStyle"/>

How can I change my xml to have an icon instead ?

回答1:

drawable_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Put your color for ripple effect -->
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/holo_green_dark">
    <item android:id="@android:id/mask">
        <shape android:shape="oval" >
        <!-- Color not displayed,just to tell ripple about the bounds -->
        <solid android:color="@android:color/black" />
        </shape>
    </item>
    <!-- And your drawable -->
    <item android:drawable="@drawable/btn_star_off_normal_holo_dark" />
</ripple>

Use this as your background for button

    android:background="@drawable/drawable_bg"

And read this about RippleDrawable It has selectors already.



回答2:

You need to download that icon (assuming it is named my_button_image.png) to your drawable directory and need to add the drawable attribute to your button,

android:background="@drawable/my_button_image"