How to get drawable resource from boolean resource

507 views Asked by At

Is there a way to get a drawable resource from a boolean resource?

For example:

bools.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="use_version_1_drawables">true</bool>
</resources>

my_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/my_drawable_version_1"/>
    <item android:drawable="@drawable/my_drawable_version_2"/>
</selector>

Is there a specific state I should be using because from what I understand they are all related to specific events (checking, focusing, etc). Perhaps I shouldn't be using a selector. I simply want to have one resource I can call upon that's actually linking to two others but will select one based on my bool.

1

There are 1 answers

8
Khodor On

You are close. You can think of a selector as an if/else statement. What you're missing now is your actual state. Here is an example:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="?attr/colorPrimaryDark" android:state_checked="true" />
    <item android:color="@color/gray" android:state_checked="false" />
</selector>

If you're using it with something like a Checkbox, then just set this selector as a drawable resource for the checkbox, and state_checked will be updated automatically.

EDIT: Problem was slightly more complex, and solved in the comments.