简体   繁体   中英

android-change button background color after clicked

Problem: I want to change the background color of a button after it has been pressed.

It's a simple problem, but I have spent a lot of time googling this and I can't seem to find a solution. They all refer to the same XML that appears below.

My XML is as follows:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/black_button_pressed" android:state_focused="true" />
    <item android:drawable="@drawable/black_button_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/black_button_normal"/>
</selector>

So, when a person hovers over a button, it'll appear grayed out. When a person clicks on a button, the button's background should be grayed out after the click, but I can't seem to get it grayed out. It returns to the normal state after the press.

Do you guys have any tips and/or pointers to help me?

In android, state of the UI will not persist after the event is completed. For example, you can handle the button click event and highlight the button but it returns to its normal state once the Up event is fired. So, the only option as far as i know is, change the background of the button by setting a different drawable resource .

btn.setBackgroundResource(R.drawable.btn_selected_blue);

This works (in your onClick handler):

button.setBackgroundResource(R.drawable.button_selected);

There may be a nicer way however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM