Java 如何将可绘制集的背景/颜色更改为视图的背景?
我的Java 如何将可绘制集的背景/颜色更改为视图的背景?,java,android,xml,Java,Android,Xml,我的drawables文件夹中有这个xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="10dp"/> <solid android:color="#fff
drawables
文件夹中有这个xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp"/>
<solid android:color="#ffffff"/>
</shape>
我基本上是用它来为我设置为背景的任何视图创建圆角。但我想知道的是如何保持视图的颜色/背景色调动态。因为假设我有三个视图,它们都需要圆角,但都需要不同的颜色,此时我必须创建三个不同的可绘制文件,并分别为每个文件设置颜色。正如我在上面的文件中所做的那样。我尝试在原始视图中使用BackgroundTint
,但它不起作用
GradientDrawable background = (GradientDrawable) textView.getBackground();
background.setColor(getResources().getColor(R.color.some_color));
我认为您已经将您的形状drawable应用到textView作为背景
因此,您需要使用已设置背景的视图来获取背景。创建可绘制背景并设置视图背景:
private void setBackground(View v, int backgroundColor) {
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setColor(backgroundColor);
shape.setSize(width, height);
shape.setCornerRadius(4.0f);
v.setBackground(shape);
v.setBackgroundDrawable(shape);
}
您可以在运行时创建一个可绘制图形,并使用它设置视图背景。