安卓通过java代码改变一个XML文件的背景。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓通过java代码改变一个XML文件的背景。相关的知识,希望对你有一定的参考价值。
我有一个Textview,背景上附加了一个XML文件。现在我想用setBackgroundColor()来改变Textview的背景,但它不起作用,因为XML文件的背景颜色必须改变。如何改变my_border XML文件的背景颜色?
XML Textview。
<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>
答案
试试这个方法
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);
以上是关于安卓通过java代码改变一个XML文件的背景。的主要内容,如果未能解决你的问题,请参考以下文章