문제

Based on the selected application theme (Dark or Light) I have two different sets of drawables (also, Dark and Light). If I need to update the state of a button, say, update the pause/play button how would I do this since I can't reference the original without knowing the current theme.

For example, 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" />

However, the following code won't compile:

mPauseButton.setImageResource(R.drawable.ic_action_pause_over_video);
도움이 되었습니까?

해결책

You can get resource id you defined for current theme in code, like:

TypedValue typedvalueattr = new TypedValue();

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

How to use styled attributes for multiple themes in XML layouts you can read there.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top