2011-01-25 67 views
1

當前使用下面的xml代碼作爲我正在製作的程序中的按鈕的背景。但是,我想動態更改我的代碼中的背景漸變。動態更改xml中定義的形狀的屬性?

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/buttonshape" 
android:shape="rectangle"> 
<gradient android:startColor="#F0F0F0" android:endColor="#A0A0A0" 
    android:angle="270" android:id="@+id/buttonGradient"/> 
<corners android:topLeftRadius="7dp" 
    android:topRightRadius="7dp" /> 
</shape> 

起初,我決定了XML應該去,我只想創建自己的類來處理這個問題。但是,我意識到沒有好的課程可以延續。 GradientDrawable沒有任何明顯的方法。 RoundRectShape沒有任何方法給我一個漸變。不過,我也不知道任何可成形的漸變/角上的訪問器。我認爲這是事實,我不明確如何定義這種形狀(我把它從其他地方使用的例子中拉出來)。我定義的每個xml視圖都將其所有屬性都包含在< />標記中。這是不同的。什麼是< gradient>和< corner>?我無法在API /開發人員工具中找到它們。我怎樣才能動態改變他們在我的代碼?

回答

2

賽斯,你可以嘗試使用GradientDrawable的重載的構造:

public GradientDrawable (GradientDrawable.Orientation orientation, int[] colors) 

這樣就可以設置梯度的方向,並且通過其中的的梯度將提供顏色的陣列。 有設定圓角的方法:

public void setCornerRadius (float radius) 

,你可以在GradientDrawable執行。

我提供這個答案,雖然我還沒有得到它的工作我自己:(也許你還會有更好的運氣

0

你可以使用一個小Xpath ..

通過「動態」我並不在什麼平臺上,但在C#下面的行可能會引導你到你的解決方案瞭解。

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load("path to xml file"); 
XmlNodeList gradientNodeList = xmlDoc.SelectNodes("//gradient"); 
foreach(XmlNode gradient in gradientNodeList){ 
    string startColor = gradient.Attributes["android:startColor"].Value; //GET 
    gradient.Attributes["android:startColor"].Value = "#FFF"; //SET Custom Value 
} 
//OR Simply 
XmlNode xn = xmlDoc.SelectSingleNode("/shape/gradient"); //and same as above 

或者,你可以使用XSLT變換您輸入的XML所需的格式。

+0

這個機器人編程(JAVA) – 2011-01-25 06:49:16