首页 > 解决方案 > Android通过java代码更改XML文件的背景

问题描述

我有一个 Textview,其背景附加了一个 XML 文件。现在我想用 setBackgroundColor() 改变 Textview 的背景,但它不起作用,因为必须改变 XML 文件的背景颜色。如何更改 my_border XML 文件的背景颜色?

XML 文本视图:

<TextView
    android:id="@+id/textView7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="150dp"
    android:background="@drawable/my_border"
    android:text="Hey"
    android:textSize="24sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

XML Textview 边框文件:

<?xml version="1.0" encoding="utf-8"?>

<!-- View background color -->
<solid
    android:color="#fff" >
</solid>

<!-- View border color and width -->
<stroke
    android:width="1dp"
    android:color="#000" >
</stroke>

<!-- The radius makes the corners rounded -->
<corners
    android:radius="5dp"   >
</corners>

<padding
    android:left="10dp"
    android:top="10dp"
    android:right="10dp"
    android:bottom="10dp">
</padding>

标签: javaandroidxml

解决方案


试试这个方法

private void recolor(Context context, TextView textView, @ColorInt int color,int drawableResourceId) {
Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, drawableResourceId);
if (unwrappedDrawable != null) {
    DrawableCompat.wrap(unwrappedDrawable);
    DrawableCompat.setTint(unwrappedDrawable, color);
    textView.setBackground(unwrappedDrawable);
    }

}

假设你想要一个红色背景,TextView那么这将如下

TextView mTextView = findViewById(R.id.textView7);

recolor(this, mTextView , getResources().getColor(R.color.red),R.drawable.my_border);

推荐阅读