Reputation: 51
this is kind of strange to ask such simple question, but I miss something somewhere and I need help.
I'm trying to change the background of a button when it clicked.
here is my code:
<Button
android:id="@+id/some_button"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:padding="5dp"
android:text="@string/somestring"
android:textAllCaps="false"
android:backgroundTint="@color/btn_background_when_selected"
android:layout_margin="5dp"
/>
Inside res folder i opened a new resource folder i called 'color' inside of it i have a file called 'btn_background_when_selected" here is what inside it -
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white"/>
<item android:state_pressed="true" android:color="@color/light_yellow" />
<item android:state_selected="true" android:color="@color/happy_green" />
</selector>
the button from the xml interacts when i added this file on the property "backgroundtint" and it became white.
on my kotlin code inside the setOnClickListener I added this -
it.isSelected=it.isSelected.not()
println(it.isSelected)
I also debugged the code to see if the button onClicked is working and i received this
2022-02-04 16:47:42.610 11419-11419/com.mypackage I/System.out: true
2022-02-04 16:47:43.560 11419-11419/com.mypackage I/System.out: false
2022-02-04 16:47:44.435 11419-11419/com.mypackage I/System.out: true
2022-02-04 16:47:45.168 11419-11419/com.mypackage I/System.out: false
every time I clicked, as aspect, the property on isSelected has changed from false to true || true to false
now my question is, although everything looks tide good enough, this is still not working, the background color still not changing, not when clicked and not on pressed.
thanks for reading,
Upvotes: 0
Views: 1273
Reputation: 19622
Try putting the default state (the white colour line) as the last line in your selector
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/light_yellow" />
<item android:state_selected="true" android:color="@color/happy_green" />
<item android:color="@color/white"/>
</selector>
selector
s work by using the first item
that matches, so you put your specific states first (pressed
, selected
etc) so it can match one of those if possible.
<item android:color="@color/white"/>
matches everything, so you put it at the end as a fallback for when nothing else has matched. If you put it first, everything will match it, so the button will be white whatever state it's in
Upvotes: 2