我在 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
并将其作为背景分配给 View ,并尝试更改 的颜色时
我遇到了这个问题。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);
关于android - GradientDrawable绘制不同颜色的setColor方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16964916/