GradientDrawable的setColor方法绘制不同的颜色

时间:2013-06-06 14:34:55

标签: android android-ui android-drawable shapedrawable

我在shape中有一个layer-list,我的目标是在运行时以编程方式更改shape的颜色。我有HEX代码的字符串,我使用Color.parseColor()来解析它,并传递给setColor方法。每当我运行应用程序时,它会显示不同的颜色,我希望。

这是我的XML文件代码:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >


<item 
    android:id="@+id/lvbg"
    android:top="1dp">
    <shape
        android:id="@+id/listview_background"
        android:shape="rectangle" >
        <size
            android:height="220dp"
            android:width="600dp" >
        </size>

        <solid android:color="@android:color/black"></solid>

        <corners android:radius="15dp" />
    </shape>
</item>
</layer-list>

这是CustomAdapter中的代码:

convertView = mInflater.inflate(R.layout.student_info_selection_fragment_icon, null);
holder = new ViewHolder();
holder.collegeBG=(LayerDrawable)convertView.getResources().getDrawable(R.drawable.rectangle);
holder.bg = (GradientDrawable)holder.collegeBG.findDrawableByLayerId(R.id.lvbg);
String color = "#FF" + rowItem.getCollegeColor();
holder.bg.setColor(Color.parseColor(color));

例如,当我放#FF1D0A63时,我会变成黑色或棕色,颜色完全不同。 感谢

2 个答案:

答案 0 :(得分:3)

我仍然不知道问题是什么,但我意识到当我在xml中使用layer-list并将其指定为视图的背景时,并尝试更改shape的颜色{ {1}}我遇到了这个问题。

所以我解决了将背景layer-listshape分开的问题。

我将背景layer-list放到另一个文件中:

shape

我将其指定为<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background" android:shape="rectangle" > <size android:height="220dp" android:width="600dp" > </size> <solid android:color="@android:color/black" > </solid> <corners android:radius="15dp" /> </shape> 的背景。

我使用TextView的原因是组合2-3个形状并使它们成为渐变并赋予它们圆角。相反,我使用layer-listView并将形状指定给它们作为背景并且它有效。

这是我的新TextView

CustomAdapter

答案 1 :(得分:2)

试试这段代码......

GradientDrawable gd = new GradientDrawable();
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke(3, Color.BLUE);
gd.setSize(w, h);
gd.setColors(new int[]{
   Color.RED,
   Color.GREEN,
   Color.YELLOW,
   Color.CYAN
});
gd.setGradientType(GradientDrawable.LINEAR_GRADIENT);