Issue
This is my custom attr:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyComponent">
<attr name="mycustom" format="boolean"/>
</declare-styleable>
</resources>
This is how I use it in layout:
<com.edu.MyComponent
style="@style/MyStyle"
app:mycustom="true"/>
It works ok in MyComponent class because I get true from this call:
typedArray.getBoolean(R.styleable.MyComponent_mycustom, false);
However, it doesn't have any effect in selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item app:mycustom="false">
(...)
</item>
<item app:mycustom="true">
(...)
</item>
</selector>
What am I doing wrong?
EDIT:
The trick was to correctly use refreshDrawableState() + onCreateDrawableState(). As to using custom attribute in selectors additionally for child elements I had to also use this:
android:duplicateParentState="true"
Solution
Step 1: declare the custom state attribute
The custom state is declared in the ‘attrs.xml’ file in the application’s ‘res/values’ directory.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyComponent">
<attr name="mycustom" format="boolean"/>
</declare-styleable>
</resources>
Step 2: use the custom state in the state list drawables
In the message list example there are two state list drawables.
One for the list item background:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:example="http://schemas.android.com/apk/res/com.charlesharley.example.android.customdrawablestates"
>
<!-- We make the pressed and focused selector items transparent so the ListView's own selector states show through. -->
<item android:state_pressed="true"
android:drawable="@android:color/transparent"
/>
<item android:state_focused="true"
android:drawable="@android:color/transparent"
/>
<item example:state_message_unread="true"
android:drawable="@color/message_list_item_background_unread"
/>
</selector>
And one for the message status icon:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:example="http://schemas.android.com/apk/res/com.charlesharley.example.android.customdrawablestates"
android:constantSize="true"
>
<item example:state_message_unread="true"
android:drawable="@drawable/message_read_status_unread"
/>
<item android:drawable="@drawable/message_read_status_read" />
</selector>
Answered By - Aniket Jain
Answer Checked By - Robin (JavaFixing Admin)