以编程方式更改自定义形状的渐变颜色

时间:2014-10-14 07:50:48

标签: android

如何更改自定义形状的背景颜色,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<inset android:insetLeft="1.0px" android:insetRight="1.0px" android:insetTop="0.0px" android:insetBottom="1.0px" xmlns:android="http://schemas.android.com/apk/res/android">
<selector>
    <item>
        <shape>
            <stroke android:width="1.0px" android:startColor="@color/grey_rounded_container_slider_start" android:endColor="@color/grey_rounded_container_slider_end" />
            <gradient android:startColor="@color/grey_rounded_container_slider_start" android:endColor="@color/grey_rounded_container_slider_end" android:angle="270.0" />
            <corners android:radius="10.0dip" />
        </shape>
    </item>
</selector>
</inset>

编程?我只需要改变渐变(背景颜色)。所以我假设我需要给渐变一个id?然后我应该如何使用view.findViewById(R.id.name)来改变我的渐变颜色?感谢。

1 个答案:

答案 0 :(得分:1)

您无法以编程方式更改drawable的颜色。或者,您可以拥有多个形状,并以编程方式更改可绘制文件。

您可以使用以下代码段以编程方式进行更改。

if(true)
    yourview.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape1))
else
    yourview.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape2))

我希望这会对你有所帮助。