应该如何代码控制shape的描边颜色啊?

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.在searchView使用该样式


      <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.需求呢,现在是这个描边颜色需要在代码中控制,也就是动态的改变样式颜色,
color.xml中没有该颜色,也不是用主题来改变

4.求助……

阅读 7.3k
3 个回答

通过 searchView.getBackground() 获取一个 GradientDrawable 对象(如果该 View 设置的是 Shape 背景的话)。

然后通过 drawable.setStroke(1, Color.RED) 动态设置描边就可以了。第一个参数 1 代表是的宽度,第二个是颜色。

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

如果整体颜色要动态变化的话, 那就是用 DrawableCompat

Drawable bg = DrawableCompat.wrap(view.getBackground());
// Need to set the background with the wrapped drawable
view.setBackground(bg);

// You can now tint the drawable
DrawableCompat.setTint(bg, ...);

传送门: Drawable 着色的后向兼容方案

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题