java - 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>
解决方案
试试这个方法
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);
推荐阅读
- json - 在 Teams 中的一个请求(Webhook)中发送多条消息
- vagrant - vagrant:尝试访问 vvv.test 时出现 404 浏览器
- android - 得到一个 gradle 构建错误。构建失败并出现异常
- c++ - 将 void 指针转换为 int
- ffmpeg - FFMPEG 脚本在每个剪辑的开头和结尾添加 1 秒淡入淡出
- c# - Unity 编辑器在运行某个功能时冻结
- excel - 两列中的 COUNTIF(S) 并获取唯一计数
- javascript - jQuery使用最接近的方法添加按钮属性
- java - 使用 Tomcat 下载扩展时出现问题
- configuration - 如何在 Pycharm 中将测试运行配置保存为默认值?