I have a selector
item in my app that is used as the background color of a listview row. The point is that the row changes color when it is being clicked / touched.
The selector therefore uses two drawables, one for the pressed state and one regular.
File: rowbgselector.xml
in folder res/color
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/rowbg_shape_selected" android:state_pressed="true"/>
<item android:drawable="@drawable/rowbg_shape" />
</selector>
The two drawables referenced are defined in res/drawable
as simple rectangle shapes with a solid color:
File rowbg_shape.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/row_bg"/>
</shape>
File rowbg_shape_selected.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="?attr/colorAccent"/>
</shape>
This works on Lollipop devices but fails on anything pre-Lollipop with an error that doesn't say much:
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/rowbg_shape_selected.xml from drawable resource ID #0x7f02006c
I believe the issue is that this is a bug that was fixed in Lollipop, see here: https://code.google.com/p/android/issues/detail?id=26251
The problem is that I'm trying to reference attr/colorAccent
which is of course defined in my themes. I have several themes with different colors which the user can choose from and attr/colorAccent
is different in all of them. However it seems due to this bug on pre-Lollipop you can't reference an attribute like this in a selector...
What are my alternative options? The only option I can think of is creating a separate selector xml file for every theme, and add something like attr/bg_selector
which then references the correct selector file for each theme. That will take me ages and further it would be a ton of work to change anything for this selector (what if I want to make the color slightly darker or lighter later, I'd have to go through all those files...).
Is there no other option?
TL;DR: I'm afraid you are correct, there is no other way to solve this issue pre-Lollipop.
I came across this question searching for an answer to a related but different issue with one of the built-in selectors (namely activatedBackgroundIndicator
as it relates to colorControlActivated
and colorAccent
). In my case, a hacky workaround was to define a color resource in the shared library and then define a color resource of the same name in each app. I don't think there is something like that for themes that is supported pre-Lollipop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With