代码修改shape的颜色属性 2018-02-28

Android常用shape定义View的背景,可以修改View的背景颜色,形状等属性

当遇到多种状态,对应多种颜色,写多个shape就不高效了
这里用代码来修改颜色的属性

GradientDrawable myGrad = (GradientDrawable)view.getBackground();
myGrad.setColor(color);

贴一段项目中的代码

   var gradientDrawable = holder.itemView.tv_corpus_status.background as (GradientDrawable)

    when (mList[position].checkStatus) {
        "0" -> {
            gradientDrawable.setColor(((mContext.get() as BaseActivity).mApp!!.resources.getColor(R.color.corpus_status_no_review)))
            holder.itemView.tv_corpus_status.text = "未审核"
        }
        "1" -> {
            gradientDrawable.setColor(((mContext.get() as BaseActivity).mApp!!.resources.getColor(R.color.corpus_status_review)))
            holder.itemView.tv_corpus_status.text = "审核中"
        }
        "2" -> {
            gradientDrawable.setColor(((mContext.get() as BaseActivity).mApp!!.resources.getColor(R.color.corpus_status_success)))
            holder.itemView.tv_corpus_status.text = "通过"
        }
        "3" -> {
            gradientDrawable.setColor(((mContext.get() as BaseActivity).mApp!!.resources.getColor(R.color.corpus_status_fail)))
            holder.itemView.tv_corpus_status.text = "未通过"
        }
    }

shape的xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
  <corners android:radius="@dimen/d10" />
</shape>

推荐阅读更多精彩内容