我有麻烦应用梯度背景到线性布局。

从我所读到的来看,这应该是相对简单的,但它似乎并不奏效。作为参考,我正在2.1-update1上开发。

header_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="90"
        android:startColor="#FFFF0000"
        android:endColor="#FF00FF00"
        android:type="linear"/>
</shape>

main_header.xml:

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

如果我改变@drawable/header_bg的颜色-例如,#FF0000,它工作得很好。我是不是遗漏了什么明显的东西?


当前回答

使用Kotlin,只需两行就可以完成

更改数组中的颜色值

                  val gradientDrawable = GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM,
                        intArrayOf(Color.parseColor("#008000"),
                                   Color.parseColor("#ADFF2F"))
                    );
                    gradientDrawable.cornerRadius = 0f;

                   //Set Gradient
                   linearLayout.setBackground(gradientDrawable);

结果

其他回答

我会检查你渐变颜色的alpha通道。对我来说,当我在测试我的代码时,我把alpha通道设置错了颜色,它不适合我。一旦我把alpha频道设置好,它就全部工作了!

我的问题是. XML扩展名没有添加到新创建的XML文件的文件名中。添加.xml扩展名解决了我的问题。

<?xml version="1.0" encoding="utf-8"?>

<gradient
    android:angle="90"
    android:startColor="@color/colorPrimary"
    android:endColor="@color/colorPrimary"
    android:centerColor="@color/white"
    android:type="linear"/>

<corners android:bottomRightRadius="10dp"
    android:bottomLeftRadius="10dp"
    android:topRightRadius="10dp"
    android:topLeftRadius="10dp"/>

我不知道这是否会帮助任何人,但我的问题是,我试图将渐变设置为ImageView的“src”属性,如下所示:

<ImageView 
    android:id="@+id/imgToast"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:src="@drawable/toast_bg"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"/>

不是100%确定为什么这没有工作,但现在我改变了它,把drawable放在ImageView的父属性的“background”属性中,在我的情况下是RelativeLayout,就像这样:(这成功地工作了)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/custom_toast_layout_id"
    android:layout_height="match_parent"
    android:background="@drawable/toast_bg">

使用Kotlin,只需两行就可以完成

更改数组中的颜色值

                  val gradientDrawable = GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM,
                        intArrayOf(Color.parseColor("#008000"),
                                   Color.parseColor("#ADFF2F"))
                    );
                    gradientDrawable.cornerRadius = 0f;

                   //Set Gradient
                   linearLayout.setBackground(gradientDrawable);

结果