【Android】使用shape的同时,动态替换shape的颜色属性

在实现布局的时候,有些按钮形状相同,只是颜色有差异,如果使用自定义shape实现了其中一种按钮,有没有可能不需要再为其他每个颜色都写一个shape文件呢?


一、问题

比如以下这三个按钮:

这里写图片描述

为第一个灰色按钮自定义背景如下:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:color="@color/gray">

    <corners
        android:radius="60dip"/>
    <stroke
        android:width="0dp"
        android:color="@color/gray" />
    <solid
        android:color="@color/gray" />
</shape>

然后,如果再为每个颜色的按钮都写一个shape背景也太麻烦,重用性太差。


二、解决方法

参考 stackoverflow 这里, 在java代码里使用 GradientDrawable 动态设置

GradientDrawable myGrad = (GradientDrawable)rectangle.getBackground();
myGrad.setColor(Color.BLACK);


【参考资料】
1、How to change solid color from the code?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值