我想围绕视图的角落,并在运行时根据内容更改视图的颜色 .
TextView v = new TextView(context);
v.setText(tagsList.get(i));
if(i%2 == 0){
v.setBackgroundColor(Color.RED);
}else{
v.setBackgroundColor(Color.BLUE);
}
v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
v.setPadding(twoDP, twoDP, twoDP, twoDP);
v.setBackgroundResource(R.drawable.tags_rounded_corners);
我希望设置一个drawable,颜色会重叠,但他们没有 . 无论我执行第二个是生成的背景 .
有没有办法以编程方式创建此视图,请记住,直到运行时才会确定背景颜色?
编辑:我现在只在红色和蓝色之间进行测试 . 之后,用户可以选择颜色 .
编辑:
tags_rounded_corners.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners
android:bottomRightRadius="2dp"
android:bottomLeftRadius="2dp"
android:topLeftRadius="2dp"
android:topRightRadius="2dp"/>
</shape>
5 回答
而不是
setBackgroundColor
,检索背景drawable并设置其颜色:此外,您可以在
tags_rounded_corners.xml
中定义填充:用于设置圆角并为视图添加随机背景颜色的总体编程方法 . 我没有测试过代码,但是你明白了 .
这里我们使用渐变drawable,以便我们可以使用
GradientDrawable#setCornerRadius
因为ShapeDrawable
没有提供任何这样的方法 .我认为最快的方法是:
您可以使用_2651668这样更好地实现它:
如果您没有中风,您可以使用
但这也会改变笔画颜色