2011-01-25 41 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