如何动态更改按下的按钮背景颜色?

时间:2010-10-24 17:19:46

标签: android

我正在开发一个问题游戏,如果答案正确,我想将答案按钮按下背景颜色变为绿色,或者如果用户按下按钮时答案错误,则将红色变为红色。

实际上我有一个custom_button.xml,我将其分配给布局中的按钮:

        <Button 
        android:id="@+id/la"
        android:width="63dp"
        android:height="65dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/la"
        android:tag="@string/la"
        android:layout_toRightOf="@+id/fa"
        **android:background="@drawable/custom_button"**
        android:layout_margin="3dp"
    />  

有没有办法在用户按下按钮时更改按钮的按下背景?

我尝试在按钮OnClickListener中使用setBackgroundDrawable(),但这会更改用户下次单击按钮时的按钮行为,而不是实际的按钮行为。

bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.custom_button_fail));

提前感谢!

1 个答案:

答案 0 :(得分:6)

  
    

我尝试在按钮OnClickListener中使用setBackgroundDrawable(),但这会更改用户下次单击按钮时的按钮行为,而不是实际的按钮行为。

  

这是因为按下按钮后会调用onClick方法。你最好的选择是:

  1. 为您的按钮创建两个不同的drawable。正常按钮的第一个按钮,当没有按下时具有正常背景,按下时为绿色背景。第二个是正常按钮,没有按下正常背景,按下红色背景。
  2. 开启onCreate,根据答案是否正确,为按钮指定正确的背景。
  3. 顺便说一下,有一个更短的方法:

    bt.setBackgroundResource(R.drawable.custom_button);
    
相关问题