我想对 View 进行圆角处理,并在运行时根据内容更改 View 的颜色。
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);
我希望设置可绘制对象和颜色会重叠,但事实并非如此。无论我第二次执行哪个都是生成的背景。
有没有办法以编程方式创建这个 View ,记住背景颜色要到运行时才会决定?
编辑:我现在只是在红色和蓝色之间交换以进行测试。稍后颜色将由用户选择。
编辑:
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>
最佳答案
检索背景可绘制对象并设置其颜色,而不是 setBackgroundColor
:
v.setBackgroundResource(R.drawable.tags_rounded_corners);
GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
drawable.setColor(Color.RED);
} else {
drawable.setColor(Color.BLUE);
}
此外,您可以在 tags_rounded_corners.xml
中定义填充:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="4dp" />
<padding
android:top="2dp"
android:left="2dp"
android:bottom="2dp"
android:right="2dp" />
</shape>
关于android - 如何以编程方式圆角并设置随机背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18391830/