【问题标题】:Android change background of an XML file via java codeAndroid通过java代码更改XML文件的背景
【发布时间】:2020-09-07 08:00:13
【问题描述】:

我有一个带有 XML 文件的 Textview 附加到背景。现在我想用 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>

【问题讨论】:

  • this回答你的问题
  • 是的,我想是的!但我不知道如何在我的程序中实现这一点

标签: java android xml


【解决方案1】:

试试这个方法

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

【讨论】:

    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 2021-06-29
    • 2016-03-11
    • 2013-05-15
    • 2021-08-06
    • 1970-01-01
    • 2017-06-15
    • 2014-02-25
    相关资源
    最近更新 更多