目前正在使用以下 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 应该去,我会创建自己的类来处理这个。但是,我意识到没有好的类(class)可以扩展。 GradientDrawable 没有任何明显的方法可以绕过角落。 RoundRectShape 没有任何方法可以给我渐变。但是,我也不知道 shapedrawable 中的渐变/角的任何访问器。我认为归根结底是我不完全理解这个形状是如何定义的(我把它从别处使用的一个例子中提取出来)。我定义的每个 xml View 的所有属性都包含在 > 标记中。这是不同的。什么是
最佳答案
Seth,你可以尝试使用 GradientDrawable 的重载构造函数:
public GradientDrawable (GradientDrawable.Orientation orientation, int[] colors)
这允许您设置渐变的方向,并传递将提供渐变的颜色数组。 有一种设置圆角的方法:
public void setCornerRadius (float radius)
您可以在 GradientDrawable 上执行。
我提供了这个答案,虽然我自己还没有让它工作:(也许你会有更好的运气。
关于android - 动态更改 xml 中定义的形状属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4790391/