Android, setSelected() and state_selected
Solution 1
The order of items matters in selector xmls, the default item should always be at the bottom in the items list.
Solution 2
not only the selected state order is important, even the order of all states is important. In my case, I added state_pressed
as first and my state_selected
doesn´t work. So I changed the order like this, and then it worked:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:state_selected="false"
android:drawable="@drawable/chooser_normal"></item>
<item
android:state_selected="true"
android:drawable="@drawable/chooser_pressed"></item>
<item
android:state_pressed="true"
android:drawable="@drawable/chooser_pressed"></item>
<item
android:state_pressed="false"
android:drawable="@drawable/chooser_normal"></item>
</selector>
EDIT
I faced now also the problem, if I press the button, it will be in the selected-state but not in pressed-state. So, the solution must be, to order the states like this and additional, it´s a good practise to add a default button look:
First, set the selected state and after this, set the same as pressed state alternately. (For now, stackoverflow isn´t showing my edit completely, don´t know why, just be patient please).
slezica
Updated on October 29, 2020Comments
-
slezica over 3 years
I'm having trouble with
View.setSelected()
.Views
are flagged as selected --TextViews
, for example, change their font color -- but my background selectors don't seem to register the change.Example selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/transparent" /> <item android:state_selected="true"> <shape android:shape="rectangle"> <solid android:color="#ff8600" /> </shape> </item> </selector>
I'm not even sure which kind of context information would be useful. The views are children of a LinearLayout, and I'm programatically setting the selected state inside a touch event. As I said, it does seem to work, since the font color goes from white to gray, but the background stays the same.
Edit: I checked for silly mistakes before posting :P. The answer is not "add the android:background attribute".