'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 1:[1]
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)
Solution 2:[2]
ResourcesCompat.getDrawable(requireActivity().resources, R.drawable.ic_baseline_arrow_back_24, null)
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sanush |
Solution 3 | Ashok |