【问题标题】:How to change background/color of the drawable set as background of a view?如何将可绘制集的背景/颜色更改为视图的背景?
【发布时间】:2018-06-07 02:51:11
【问题描述】:

我的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,但它不起作用。

【问题讨论】:

  • 你可以在运行时创建一个drawable,并用它设置你的视图背景。

标签: java android xml


【解决方案1】:
GradientDrawable background = (GradientDrawable) textView.getBackground();
background.setColor(getResources().getColor(R.color.some_color));

我认为您已将可绘制的形状应用到 textView 作为背景。

因此,您需要使用设置了背景的视图来获取背景。

【讨论】:

    【解决方案2】:

    创建一个可绘制的背景并设置您的视图背景:

    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);
    }
    

    【讨论】: