如何在Android中将一个布局视图的背景颜色设置为渐变色?

35

我该如何指定 Android 布局视图元素的背景“颜色”为渐变色(特定角度)?

我希望在 XML 中指定,而不是在运行时指定。最好作为一个样式,我可以将其应用于任何我想要的布局,并使用 style 属性。

3个回答

99

/res/drawable中创建gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFFFF"
        android:endColor="#00000000"
        android:angle="45"/>    
</shape>

在你的 /res/layout 目录下的 main.xml 布局文件中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/gradient"
    >   
</LinearLayout>

您可以通过替换android:angle的值来指定角度,并通过替换android:startColorandroid:endColor来指定起始/结束颜色。


我们能在运行时更改XML渐变值吗? - Akash kumar

10
您可以使用类似以下的方式:

您可以采用以下方法:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
    <gradient android:startColor="#A1A1A1" 
              android:centerColor="#BDBDBD"
              android:endColor="#A4A4A4" 
              android:angle="-90" />
</shape>

创建一个渐变(您可以选择喜欢的颜色)。将其放置在drawable目录中,然后您就可以将其用作背景:android:background="@drawable/您的xml文件名"


5

这是我设置渐变样式的方法。希望对您有所帮助。但是我使用的是textview。也许您需要根据您的布局背景进行一些更改。

            Shader textShader = new LinearGradient(0, 0, 0, 20, new int[] {
            Color.WHITE, getResources().getColor(//some color),
            getResources().getColor(//some color), Color.WHITE },
            new float[] {  0.25f,0.50f,0.75f, 1 }, TileMode.CLAMP);
            textview.getPaint().setShader(textShader);

2
虽然他在问题中提到他想要一个XML解决方案,而不是运行时解决方案。 - DonGru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接