2015-04-07 10 views
0

我是android開發新手,目前正在製作計算器應用程序。其中,我的活動有一些按鈕,我應用了相同的風格。代碼的結構是一樣的東西,如下以編程方式更改style.xml中item的值android

layout.xml <LinearLayout> <Button android:text="Button 1" style="@style/styleName" > <Button android:text="Button 2" style="@style/styleName" > <Button android:text="Button 3" style="@style/styleName" > </LinearLayout> style.xml

<resources> <style name="styleName"> <item name="attribute1">attribute1Value</item> <item name="attribute2">attribute2Value</item> <item name="attribute3">attribute3Value</item> <item name="android:background">BackgroundValue</item> </style> </resources>

現在我想提供一個功能,用戶在其中時,他/她從設置中選擇一個特定的主題,所有按鈕的背景將改變。如果我可以在styleName中更改背景顏色的值,就可以實現這一點。我不知道如何實現這一點。我環顧網絡,並沒有找到任何令人滿意的答案來實現相同的目標。

+0

http://stackoverflow.com/questions/13719103/how-to-retrieve-style-attributes-programatically-from-styles-xml你試試這個? – Amsheer

回答

0

您可以通過Typed數組訪問style xml的屬性。 假設你有一個customstyle xml。

int[] attrs ={android.R.attr.textColor, android.R.attr.background,android.R.attr.text}; 
TypedArray array = obtainStyledAttributes(R.style.CustomStyle, attrs); 

// Fetching the colors defined in your style 
int textColor = array.getColor(0, Color.BLACK); 
int backgroundColor = array.getColor(1, Color.BLACK); 
0

顯然,你不能改變風格programmatically.if我是你,我會創造很多selector.xml/res/drawable/這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item 
    android:state_pressed="true" 
    android:drawable="@drawable/light_btn_pressed" /> 
    <item 
    android:state_pressed="false" 
    android:drawable="@drawable/light_btn_normal" /> 
</selector> 

對於每一個「風格」,你將有一個選擇器(光,黑暗,..等)。 插入可繪製的顏色或圖像。 之後,您可以通過設置android:background="@drawable/my_button"來應用這些選擇器。 另外,使用此方法,您還可以實現按鈕狀態的交互。

我希望它能幫助

+0

請記住,並非所有sdks都支持相同的主題。 –

相關問題