我有一个用 xml 定义的可绘制椭圆,白色背景。我将此圈设置为gridAdapter中textView
的背景资源。
我想通过代码更改可绘制圆圈的颜色,而且我没有太多运气。我使用过.setColor
,.setColorFilter
和其他各种黑客,但都没有。圆圈在textView
的背景中加载为白色,它似乎永远不会改变。
在这里,我尝试加载drawable并修改其颜色,然后将其作为背景资源添加到textView
:
int color = Color.parseColor(locationModel.col_line_color); // Color of the line
GradientDrawable bgcircle = (GradientDrawable) gridContext.getResources().getDrawable(R.drawable.circle);
bgcircle.mutate();
// bgcircle.setColor(color);
bgcircle.setColorFilter(color, Mode.SRC_ATOP);
viewHolder.textView.setText((locationModel.col_line).toString());
viewHolder.textView.setBackgroundResource(R.drawable.circle);
可绘制形状的XML:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@android:color/white"/>
<size
android:width="120dp"
android:height="120dp"/>
</shape>
许多教程要求.mutate()
然后实现.setColorFilter()
,但我没有太多运气。我已经尝试将PorterDuff模式更改为一些替代方案,但圆圈继续呈现白色。
任何帮助/指导都将不胜感激。
答案 0 :(得分:2)
不要尝试修改当前的xml drawable,而是在代码中创建drawable。如果你不需要渐变,你也可以使用ShapeDrawable。
ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(newColor);