【问题标题】:Change image resource using attributes and themes使用属性和主题更改图像资源
【发布时间】:2011-07-11 14:00:13
【问题描述】:

我不知道如何在代码中更改 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 属性更改它,以便我可以为不同的主题使用不同的图像?

【问题讨论】:

    标签: java android attributes android-layout themes


    【解决方案1】:

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

    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>
    

    【讨论】:

      【解决方案2】:

      我仍然不知道如何以编程方式访问主题中的样式,所以我不得不使用带有两个单独按钮的技巧。每个都有自己的样式,而不是更改一个按钮的图像/样式,我正在设置两个样式按钮的可见性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 2014-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多