我不知道如何在代码中更改 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/