要在代码中改变xml文件中shape属性,可以用GradienDrawable,例如我给一个button自定义了一个背景,名small_button
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/background_primary"/>
<stroke android:width="2dp" android:color="@color/red_primary"/>
<corners android:radius="10dp"/>
</shape>
,然后给button设置
android:background="@drawable/small_shape"
但是想实现动态变化背景色,所以需要在代码中改变背景色,但是不改变我设置的其他样式,比如边框颜色和圆弧角,
GradientDrawable mgd = (GradientDrawable) button.getBackground();//这里先设置改背景
mgd.setColor(ContextCompat.getColor(context,backgroundColor));//这里设置改背景的颜色
转载请注明原文地址: https://ju.6miu.com/read-16683.html