我该如何指定 Android 布局视图元素的背景“颜色”为渐变色(特定角度)?
我希望在 XML 中指定,而不是在运行时指定。最好作为一个样式,我可以将其应用于任何我想要的布局,并使用 style
属性。
我该如何指定 Android 布局视图元素的背景“颜色”为渐变色(特定角度)?
我希望在 XML 中指定,而不是在运行时指定。最好作为一个样式,我可以将其应用于任何我想要的布局,并使用 style
属性。
在/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:startColor
和android:endColor
来指定起始/结束颜色。
您可以采用以下方法:
<?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文件名"
这是我设置渐变样式的方法。希望对您有所帮助。但是我使用的是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);