通过GradientDrawable设置或修改view background

本文介绍如何利用GradientDrawable在不改变圆角属性的情况下,动态地改变Android应用中视图的背景颜色。通过示例代码展示了如何设置特定形状及颜色,并在Java代码中更新颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中遇到根据后台数据修改view背景色的要求。通过setBackground(color),虽然改变了颜色,但是也改变了圆角属性。

这里可以通过使用GradientDrawable来修改已经设置的shape中的颜色来达到目的。

比如,上图中TextView通过设置background实现上面左上、右下圆角的效果:

<TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="4dp"
        android:paddingTop="4dp"
        android:paddingRight="8dp"
        android:paddingLeft="8dp"
        android:background="@drawable/bg_text"
        android:text="理财"
        android:textSize="14sp"
        android:textColor="#ffffff"/>


bg_text.xml中代码:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/red_f3323b"/>

    <corners
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="0dp"/>

</shape>


然后,在JAVA代码获取view的背景,然后再修改背景的颜色,便能实现只替换颜色。

GradientDrawable gd = (GradientDrawable)textview.getBackground();
gd.setColor("#679432");
holdView.typeTv.setBackground(gd);

同样,也可以直接在JAVA代码中直接设置背景

int roundRadius = 15;
int fillColor = Color.parseColor("#679432");
GradientDrawable gd = new GradientDrawable();
drawable gd.setColor(fillColor);
gd.setCornerRadius(roundRadius); //或者使用gd.setCornerRadii(new float[]{15,15,15,15,15,15,15,15})
textview.setBackground(gd);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值