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

时间:2011-07-11 14:00:14

标签: java android attributes android-layout themes

我无法弄清楚如何在代码中更改ImageButton的图像资源。我在themes.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属性更改它,以便我可以为不同的主题使用不同的图像?

2 个答案:

答案 0 :(得分:3)

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

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>

答案 1 :(得分:0)

我仍然不知道如何从主题programaticaly访问样式,所以我不得不使用两个单独按钮的技巧。每个都有自己的风格,而不是改变一个按钮的图像/风格,我设置两个风格的按钮的可见性。