我在layer-list
中有一个shape
,我的目标是在运行时以编程方式改变shape
的颜色。我有字符串十六进制代码,我用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
时,我得到黑色或棕色,完全不同的颜色。由于
我仍然不知道问题是什么,但我意识到,当我在xml中使用layer-list
并将其分配为视图背景时,并尝试在layer-list
中改变shape
的颜色,我遇到了这个问题。
所以我解决了它分离我的背景shape
从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
的背景。
我使用layer-list
的原因是组合2-3个形状,使它们渐变并给它们圆角。相反,我使用View
和TextView
,并将形状分配给它们作为背景,效果很好。
这是我的新CustomAdapter
:
convertView = mInflater.inflate(R.layout.student_info_selection_fragment_icon, null);
holder = new ViewHolder();
holder.tvBackground = (TextView) convertView.findViewById(R.id.tvSelectionCollegeBackground);
GradientDrawable background = (GradientDrawable) holder.tvBackground.getBackground();
String color = "#FF" + rowItem.getCollegeColor();
background.setColor(Color.parseColor(color));
holder.tvBackground.setBackground(background);
试试这段代码…
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);