androidkotlinandroid-resourcesandroid-attributes

How to retrieve drawable from attributes reference in a Fragment


Can someone confirm what the correct way is to retrieve drawable from attributes reference (from a fragment)?

activity.context in val myDrawable = ContextCompat.getDrawable(activity.context, imageResId) ?: throw IllegalArgumentException("Cannot load drawable $imageResId") returns this error:

Unresolved reference: context

I'm unsure which context should be used here.

Here is some relevant code:

val typedValue = TypedValue()
activity!!.theme.resolveAttribute(R.attr.imgSearch, typedValue, true)
val imageResId = typedValue.resourceId
val myDrawable = ContextCompat.getDrawable(activity.context, imageResId) ?: throw IllegalArgumentException("Cannot load drawable $imageResId")

Solution

  • Try the following:

    activity.resources.getDrawable(imageResId)
    

    Update: getDrawbale() is depricated from api 22, in that case you can try the following:

    ResourcesCompat.getDrawable(activity!!.resources, imageResId, null)