如何设置3种不同状态的按钮

时间:2018-06-10 08:09:46

标签: android button

我试图创建自己的西蒙版本说。我想为按钮创建三种状态(颜色); off(false),闪烁按下(true)。如果我使用mButton1.setbackgroundColor(Color.Red),我将丢失XML按钮样式。如何在不丢失XML样式的情况下完成此操作,或者是否有更好的方式来设置按钮的样式。

1 个答案:

答案 0 :(得分:1)

您可以在button selector目录中创建drawable xml,如下所示。它定义了当按钮处于不同状态时使用的不同drawable,例如:default,pressed等等。

drawable/my_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- pressed -->
    <item android:state_pressed="true" android:drawable="@drawable/my_button_pressed" />

    <!-- focused -->
    <item android:state_focused="true" android:drawable="@drawable/my_button_pressed" />

    <!-- selected -->
    <item android:state_selected="true" android:drawable="@drawable/my_button_pressed" />

    <!-- default -->
    <item android:drawable="@drawable/my_button_default" />
</selector>

然后,为不同的状态定义相应的drawable xml

drawable/my_button_default.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!-- define this color in your colors.xml  -->
    <solid android:color="@color/default_button_color"/>

    <!-- this makes the rounded corners button -->
    <corners android:radius="5dp" />
</shape>

drawable/my_button_pressed.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!-- define this color in your colors.xml  -->
    <solid android:color="@color/pressed_button_color"/>

    <corners android:radius="5dp" />
</shape>

您现在可以使用定义drawable/my_button_selector的{​​{1}}中的xml

button

请注意,对于<Button android:id="@+id/my_button" android:background="@drawable/my_button_selector" android:layout_width="200dp" android:layout_height="160" android:text="My Button" /> ,您可以使用默认的API Level 21 or higher效果。将以下ripple放在my_button_selector.xml目录下:

drawable-v21

drawable-v21/my_button_selector.xml

有了这个,Android将<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_material_light"> <item android:id="@android:id/mask"> <shape android:shape="rectangle"> <solid android:color="@android:color/white" /> <corners android:radius="5dp" /> </shape> </item> <item android:drawable="@drawable/my_button_default" /> </ripple> 用于v21/my_button_selector.xml。对于低于此级别的API级别,它使用API Level 21 or higher

相关问题