我想点击按钮时改变按钮的颜色?

时间:2012-11-27 16:06:32

标签: android button widget

  

可能重复:
  How to Change color of Button in Android when Clicked?

点击时我想改变按钮的颜色...... 我怎么能这样做?我不想通过使用drawable文件夹来实现...

1 个答案:

答案 0 :(得分:2)

使用selector,在drawable/文件夹中创建文件xml,并将其命名为bg_button.xml

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

    <item android:drawable="@drawable/back_button_clicked" android:state_pressed="true"></item>
    <item android:drawable="@drawable/back_button_clicked" android:state_focused="true"></item>
    <item android:drawable="@drawable/back_button_normal"></item>

</selector>

然后在你的xml布局中,像这样定义你的按钮:

<Button android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_button" />

NB back_button_clickedback_button_normal drawablesbutton的背景。 当点击时,可绘制的back_button_clicked将成为您按钮的背景,而正常情况中,back_button_normal将成为您按钮的背景

编辑:这里有tutorial以获得更多解释。这是another one