How to retrieve drawable from attributes reference in a Fragment

4.6k Views Asked by At

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")
3

There are 3 best solutions below

1
Md Golam Rahman Tushar On BEST ANSWER

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)
0
Ashok On

The reason of Unresolved reference: context is that there is no such #getContext method present with activity.

Since in ContextCompat.getDrawable(activity.context, imageResId) the activity.context would try to make a call to activity#getContext, since the method is not present, this exception is throw.

Try updating this statement to ContextCompat.getDrawable(activity, imageResId) as activity is itself an instance of context.

0
Sanush On
ResourcesCompat.getDrawable(requireActivity().resources, R.drawable.ic_baseline_arrow_back_24, null)