GradientDrawable类的利用动态设置样式中的颜色

1.xml样式文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 角度 -->
    <corners android:radius="2dp"/>
    <!-- 填充色 -->
    <solid  android:color="#ffffff"/>
    <!-- 描边 设置线宽及颜色 -->
    <stroke android:color="@color/colorAccent"
        android:width="1dp"/>
</shape>

2.Search中使用该样式

      <android.support.v7.widget.SearchView
            android:id="@+id/searchView_singer"
            android:layout_width="match_parent"
            android:layout_height="46dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/searviewtest"
            />

3.需求呢,现在是这个描边颜色需要在代码中控制,也就是动态的改变样式颜色,

 

通过 searchView.getBackground() 获取一个 GradientDrawable 对象(如果该 View 设置的是 Shape 背景的话)。
然后通过 drawable.setStroke(1, Color.RED) 动态设置描边就可以了。第一个参数 1 代表是的宽度,第二个是颜色。

        GradientDrawable gradientDrawable1= (GradientDrawable) searchView.getBackground();
        gradientDrawable1.setStroke(3, xColor);
        searchView.setBackground(gradientDrawable1);

  

posted @ 2017-06-27 09:12  咖喱不见不散啊  阅读(2600)  评论(0编辑  收藏  举报