Android 如何从片段中的属性引用中检索drawable

Android 如何从片段中的属性引用中检索drawable,android,kotlin,android-resources,android-attributes,Android,Kotlin,Android Resources,Android Attributes,有人能确认从片段的属性引用中检索drawable的正确方法吗 val myDrawable=ContextCompat.getDrawableactivity.context中的activity.context,imageResId?:抛出IllegalArgumentException无法加载drawable$imageResId返回此错误: 未解析引用:上下文 我不确定这里应该使用哪种上下文 以下是一些相关代码: val typedValue = TypedValue() activity!

有人能确认从片段的属性引用中检索drawable的正确方法吗

val myDrawable=ContextCompat.getDrawableactivity.context中的activity.context,imageResId?:抛出IllegalArgumentException无法加载drawable$imageResId返回此错误:

未解析引用:上下文

我不确定这里应该使用哪种上下文

以下是一些相关代码:

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")
请尝试以下操作:

activity.resources.getDrawable(imageResId)
更新:GetTrable已从api 22中删除,在这种情况下,您可以尝试以下操作:

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

如果您参加活动,您可以使用:

ContextCompat.getDrawable(activity, imageResId)
未解析reference:context的原因是活动中不存在此类getContext方法

由于在ContextCompat.getDrawableactivity.context中,activity.context将尝试调用activitygetContext,由于该方法不存在,因此将引发此异常


尝试将此语句更新为ContextCompat.getDrawableactivity,imageResId因为activity本身就是上下文的实例。

API 22中不推荐使用此语句
ResourcesCompat.getDrawable(requireActivity().resources, R.drawable.ic_baseline_arrow_back_24, null)