2012-01-06 22 views
5

我正在使用自定義屬性來實現我的應用程序中的主題切換。我有以下屬性定義:setTextAppearance通過代碼引用自定義屬性

<resources> 
    <attr name="TextAppearance_Footer" format="reference"></attr> 
</resources> 

我有不同的定義此屬性的兩個主題:

<style name="NI_AppTheme.Dark"> 
    <item name="TextAppearance_Footer">@style/Footer</item> 
</style> 

@style/Footer定義如下:

<style name="Footer" parent="@android:style/TextAppearance.Large"> 
    <item name="android:textColor">#00FF00</item> // Green 
</style> 

現在,如果我嘗試將此款式設置爲TextView使用:

textView.setTextAppearance(this, R.attr.TextAppearance_Footer); 

它不起作用(即不會將文本設置爲綠色)。但是,如果我通過xml指定文本外觀使用:

android:textAppearance="?TextAppearance_Footer" 

它工作正常。我可能會錯過什麼?我需要設置屬性,因爲我想動態地在主題之間切換。

附加信息:

如果我使用:

textView.setTextAppearance(this, R.style.NI_AppTheme.Dark); 

看來工作沒事。

編輯:測試工作方案(感謝@nininho):

Resources.Theme theme = getTheme(); 
TypedValue styleID = new TypedValue(); 
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) { 
    channelTitle.setTextAppearance(this, styleID.data); 
} 

回答

11

爲什麼不使用:

textView.setTextAppearance(this, R.style.Footer); 

我認爲textAppearance必須是一個風格。

編輯:

也許你應該試試這個:

TypedArray a = context.obtainStyledAttributes(attrs, 
new int[] { R.attr.TextAppearance_Footer }); 

int id = a.getResourceId(R.attr.TextAppearance_Footer, defValue); 
textView.setTextAppearance(this, id); 

編輯: 正確的測試代碼:

Resources.Theme theme = getTheme(); 
TypedValue styleID = new TypedValue(); 
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) { 
    channelTitle.setTextAppearance(this, styleID.data); 
} 
+0

因爲可能他希望通過主題選擇此選項,而不是直接使用R.style.Footer。 – aromero 2012-01-06 12:46:35

+0

所以他應該使用的主題,但從他不想使用它的問題(不知道爲什麼) – 2012-01-06 12:56:09

+0

不確定是這種情況。他試圖做的是將TextAppearance樣式委託給主題。 TextAppearance_Footer是鏈接的屬性,例如,假設您有theme1和theme2。 theme1會說TextAppearance_Footer => textAppearance1和theme2會說TextAppearance_Footer => textAppearance2。在你的小部件中,你只需說textAppearance => TextAppearance_Footer。你得到的是一個基於當前主題的自動樣式鏈接 – aromero 2012-01-06 13:03:22