如何以编程方式将attr值分配给ImageView?

时间:2020-07-22 11:18:04

标签: android android-imageview android-resources android-theme

我正在尝试通过选择适当的图像在应用中应用暗模式。我已定义资源editorConfig: { toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ], } 用于选择图像,如下所示

attr

以下指向我的<resources> <attr name="postStarTrue" format="reference"/> </resources> 的“亮与暗”主题

style.xml

在访问这些样式时,我收到以下代码的异常和警告。

<style name="LightTheme" parent="AppTheme">
    <item name="postStarTrue">@drawable/star_post_true</item>
</style>

<style name="DarkTheme" parent="AppTheme">
    <item name="postStarTrue">@drawable/star_post_true_dark</item>
</style>

错误/警告:

PostStarredImg.setImageResource(R.attr.postStarTrue);

添加此皮棉后,我的应用程序崩溃并清除了Logcat。请帮助我从attr访问我的图像资源。

例外:

Supress: Add SupressLint("ResourceType")

当我直接访问图像资源时,我的代码工作正常

E/com.test: Resource 7f030259 is a complex map type.
? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test, PID: 7849
    android.content.res.Resources$NotFoundException: Resource ID #0x7f030259

1 个答案:

答案 0 :(得分:0)

尝试以下代码从主题中设置的属性中获取价值:

wall2

在Java中可以是:

activity?.obtainStyledAttributes(intArrayOf(R.attr.postStarTrue))?.use {
    PostStarredImg.setImageDrawable(it.getDrawable(0))
}