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

【字号: 作者:雯心浏览:34日期:2022-10-28

问题描述

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: /></shape>

2.在searchView使用该样式

<android.support.v7.widget.SearchView android: 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.求助……

问题解答

回答1:

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

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

回答2:

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));}

相关文章: