2014-05-11 173 views
1

基於選定的應用程序主題(黑暗或光明),我有兩套不同的繪圖(也是黑暗和光明)。如果我需要更新按鈕的狀態,比如說,更新暫停/播放按鈕,我該如何做到這一點,因爲我不能在不知道當前主題的情況下引用原始圖片。以編程方式基於主題的Android更改按鈕

例如,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

你可以得到的資源ID您在代碼中爲當前主題定義,如:

TypedValue typedvalueattr = new TypedValue(); 

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

如何在XML佈局中爲多個主題使用樣式屬性,您可以閱讀there

+0

謝謝,這工作! –

相關問題