java - 使用属性和主题更改图像资源

标签 java android attributes android-layout themes

我不知道如何在代码中更改 ImageButton 的图像资源。我在 theme.xml 中定义了以下主题:

<resources>
   <style name="MMTheme.Blue">
        <item name="playButtonImg">@drawable/play_button</item>
        <item name="pauseButtonImg">@drawable/pause_button</item>
   </style>
</resources>

属性在 attrs.xml 中定义:

<resources>
    <attr name="pauseButtonImg" format="integer"/>
    <attr name="playButtonImg" format="integer"/>
</resources>

现在我想更改ImageButton的图像资源。我可以通过以下方式更改它:

playButton.setImageResource(R.drawable.play_button);

但我想使用主题。如何使用 playByttonImg 属性更改它,以便我可以为不同的主题使用不同的图像?

最佳答案

现在我有了原始问题的解决方案:

public static int getStyledDrawableId(Context context, int attribute)
{
    TypedArray a = context.getTheme().obtainStyledAttributes(new int[] { attribute });
    int id = a.getResourceId(0, -1);
    return id;
}

当我调用时,它会返回一个可绘制的 id,例如: getStyledDrawableId(getContext(), R.attr.playButtonImg) 。上下文必须具有选定的主题集。

属性应更改为引用格式:

<resources>
    <attr name="pauseButtonImg" format="reference"/>
    <attr name="playButtonImg" format="reference"/>
</resources>

关于java - 使用属性和主题更改图像资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6651262/

相关文章:

.net - 如何将生成的方法标记为过时?

c++ - _attribute(section ("NC_BSS")...这是什么意思?

使用 Netbeans 的 REST Web 服务的 Java 客户端

java - 使用 Google map PlacePicker API 时,我得到了错误的地名(获取坐标)

java - ECDH 服务器 key 交换消息上的签名无效

android - 不同包中的相同库不起作用

android - 切换已经膨胀的 stubview 布局的正确方法是什么?

java - 阶乘误差之和

android - 如何使用 VSCode 获取 FirebaseInstanceId?

.net - 您可以在运行时评估方法的属性吗?