3

I have a RecyclerView with a ConstraintLayout as the root View of each item.

I am setting the ConstraintLayout background as a selector, the selector is defined as:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="?attr/selectableItemBackground" android:state_pressed="true" />
    <item android:drawable="@color/colorAccent" android:state_activated="true" />
    <item android:drawable="@android:color/transparent" />
</selector>

My goal was to have the ripple effect when an item is pressed, and change the item's background to the accent color when the item is selected.

The problem is, selectableItemBackground works on any View's background, but if I place it on the selector as it is, my app crashes as soon as the ConstraintLayout is inflated.

If I remove the ?attr/selectableItemBackground and substitute it for any color, the selector works just fine.

Here's the simplified crash error on Logcat:

android.view.InflateException: Binary XML file line #0: Binary XML file line #0: 
        Error inflating class android.support.constraint.ConstraintLayout                                                                 
Caused by: android.view.InflateException: Binary XML file line #0: 
        Error inflating class android.support.constraint.ConstraintLayout                                                                            
Caused by: java.lang.reflect.InvocationTargetException
Caused by: android.content.res.Resources$NotFoundException: 
        Drawable com.test.test:drawable/list_item_background_selector with resource ID #0x7f080086
Caused by: android.content.res.Resources$NotFoundException: 
        File res/drawable/list_item_background_selector.xml from drawable resource ID #0x7f080086
Michel Feinstein
  • 13,416
  • 16
  • 91
  • 173
  • Why not `android:foreground="android:?attr/selectableItemBackground"` on the XML layout, then set your background as you wish? – Mark Nov 13 '17 at 01:07
  • 1
    That works! Great idea...but still it bugs me why it doesn't work on the selector...I usually like to understand why something doesn't work, and not just settle for a workaround...any clues what's happenings? – Michel Feinstein Nov 13 '17 at 01:18
  • Not without delving into the source. Although I don't like the term "Whatever works" sometimes life is easier settling with it! – Mark Nov 13 '17 at 01:22
  • yeah, that should be on a t-shirt for coders or something ... – Michel Feinstein Nov 13 '17 at 01:24
  • Just for reference, this [answer](https://stackoverflow.com/a/36424426/8781554) seems to do the trick. – Xam Mar 25 '21 at 19:40

0 Answers0