【问题标题】:Set the background colour of a Layout view to a gradient in Android?在Android中将布局视图的背景颜色设置为渐变?
【发布时间】:2014-11-14 18:29:14
【问题描述】:

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

我希望在 XML 中指定它,即不在运行时指定。最好作为一种样式,我可以通过style 属性应用于我希望的任何布局?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    /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>
    

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

    <?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 渐变值吗
    【解决方案2】:

    你可以这样使用:

    <?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/the_name_of_your_xml"

    【讨论】:

      【解决方案3】:

      这就是我设置渐变样式的方式。希望这可以帮助。但我已经将它用于文本视图。也许您必须进行一些更改以适应您的布局背景。

                  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);
      

      【讨论】:

      • 虽然他在问题中提到他想要一个 xml 解决方案,而不是运行时解决方案
      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 2015-02-14
      • 2011-11-14
      • 2015-02-15
      • 2021-03-11
      相关资源
      最近更新 更多