动态更换 Shape 的颜色

android为我们是提供了在代码中动态设置 shape 的颜色的方法。

  1. 首先,shape代码是这样的
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:height="18dp" android:width="18dp"/>
    <solid android:color="#2A98FF" />
</shape>
  1. 然后,在 xml 中使用
<ImageView
        android:id="@+id/shape"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center"
        android:background="@drawable/shape_bg"
        android:padding="6dp"
        android:src="@mipmap/ic_launcher" />
  1. 最后,在代码中动态设置shape的颜色
    代码如下:
 ImageView imageView = helper.getView(R.id.shape);
 GradientDrawable grad  = new GradientDrawable();
 grad.setColor(ContextCompat.getColor(this, R.color.red));
 grad.setShape(GradientDrawable.OVAL);
 imageView.setBackground(grad);
  1. colors 里的颜色值
<color name="red">#FF453A</color>

通过上面简单的几行代码就可以动态的设置shape的颜色。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容