How to dynamically change a pressed button background color?
I'm developing a question game and I want to change the answer button pressed background color to green if the answer is correct or to red if the answer is wrong just in the moment the user press the button.
Actually I have a custom_button.xml which I assign to the buttons in the layout:
<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"
/>
Is there a way to change the pressed background of a button just in the moment the user is pressing the button?
I tried using setBackgroundDrawable() inside the button OnClickListener but this change the button behaviour for the next time the user click t开发者_StackOverflowhe button, not the actual.
bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.custom_button_fail));
thanks in advance!
I tried using setBackgroundDrawable() inside the button OnClickListener but this change the button behaviour for the next time the user click the button, not the actual.
That's because the onClick
method is called after the button is pressed. Your best choice here is:
- Create two different drawables for your buttons. 1st for a normal button with normal background when it's not pressed and green background when pressed. 2nd for a normal button with normal background when it's not pressed and red background when pressed.
- On
onCreate
assign the correct background to the buttons depending on whether the answer would be correct or not.
By the way, there is a shorter way to do so:
bt.setBackgroundResource(R.drawable.custom_button);
精彩评论