Android更改按钮以编程方式基于主题

时间:2014-05-11 23:48:02

标签: android themes

根据选定的应用主题(黑暗或光明),我有两套不同的drawable(也就是Dark和Light)。如果我需要更新按钮的状态,比如说,更新暂停/播放按钮,我将如何执行此操作,因为我无法在不知道当前主题的情况下引用原始文件。

例如,styles.xml

<style name="Theme.ServeStream.Dark" parent="@style/Theme.AppCompat">
    <item name="attr/ic_action_pause_over_video">@drawable/ic_action_pause_over_video_dark</item>
    <item name="attr/ic_action_play_over_video">@drawable/ic_action_play_over_video_dark</item>
    <item name="attr/ic_action_previous">@drawable/ic_action_previous_dark</item>
    <item name="attr/ic_action_next">@drawable/ic_action_next_dark</item>
</style>

<style name="Theme.ServeStream.Light" parent="@style/Theme.AppCompat.Light">
    <item name="attr/ic_action_pause_over_video">@drawable/ic_action_pause_over_video_light</item>
    <item name="attr/ic_action_play_over_video">@drawable/ic_action_play_over_video_light</item>
    <item name="attr/ic_action_previous">@drawable/ic_action_previous_light</item>
    <item name="attr/ic_action_next">@drawable/ic_action_next_light</item>
</style>

attrs.xml:

<attr name="ic_action_pause_over_video" format="reference" />
<attr name="ic_action_play_over_video" format="reference" />
<attr name="ic_action_previous" format="reference" />
<attr name="ic_action_next" format="reference" />

但是,以下代码将无法编译:

mPauseButton.setImageResource(R.drawable.ic_action_pause_over_video);

1 个答案:

答案 0 :(得分:1)

您可以在代码中获取为当前主题定义的资源ID,例如:

TypedValue typedvalueattr = new TypedValue();

getTheme().resolveAttribute(R.attr.ic_action_pause_over_video, typedvalueattr, true);
mPauseButton.setImageResource(typedvalueattr.resourceId);

如何在XML布局中为多个主题使用样式属性,您可以阅读there