Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 210
user1399797 Avatar asked Oct 08 '22 14:10

user1399797


1 Answers

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);
like image 107
Prem Avatar answered Oct 12 '22 12:10

Prem