Android shape动态修改颜色
Android 成长在于积累和分享
本文:https://www.jianshu.com/p/9ec153ba03d8
文章目录
- 前言
- 解决方案
- 修改Solid颜色
- 修改Stroke颜色
- Shape
- shape对应的GradientDrawable
- GradientDrawable
- 修改solid颜色
- 修改Stroke颜色
- 结语
- 参考文献
前言
Andoid 中很多圆角或者边线的操作都喜欢用 shape 实现。
那么很多需求会用到根据特定的状态去展示当前的颜色,这个时候,可能就需要动态修改 shape 的颜色了。
当然也有小伙伴选择直接重写几个shape代表不同的状态。哈哈。
除此之外,也可以考虑使用material中的相关View实现,这个后话在说。
解决方案
答案要写在前面,分析可以后面慢慢看
修改Solid颜色
// Java
GradientDrawable shapeDrawable = (GradientDrawable) mShapeView.getBackground();
shapeDrawable.setColor(mShapeView.getResources().getColor(color));// kotlin
val shapeDrawable = mShapeView.background as GradientDrawable
shapeDrawable.setColor(mShapeView.resources.getColor(color))
修改Stroke颜色
// Java
GradientDrawable shapeDrawable = (GradientDrawable) mShapeView.getBackground();
shapeDrawable.setStroke((int)Utils.dpToPx(mContext,1),mShapeView.getResources().getColor(color));// kotlin
val shapeDrawable = mShapeView.background as GradientDrawable
shapeDrawable.setStroke(1.dp,mShapeView.resources.getColor(color))
Shape
假设我现在有一个正在使用的 shape 了,
一个底部左右圆角,带白色边框红色内部的样式
如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><cornersandroid:bottomLeftRadius="6dp"android:bottomRightRadius="6dp"/><stroke android:width="1dp"android:color="@color/white" /><solid android:color="@color/red"/></shape>
大致效果如图:
shape对应的GradientDrawable
首先,我们先确认shape对应的Drawable是哪个,这个可以通过Debug查看。
可以通过layout的xml设置给 background
或者在代码中直接通过 getResource().getDrawable(resId)
debug结果如图:
结果显示:
shape对应的Drawable为 GradientDrawable
GradientDrawable
然后我们再看GradientDrawable的源码。
在注释说明中确认了,shape最终对应的就是GradientDrawable
并且在xml中定义的属性,都可以看得到。
条件允许的话,可以通篇看一遍源码。
这里只摘录了一部分。
package android.graphics.drawable;import .../*** A Drawable with a color gradient for buttons, backgrounds, etc.** <p>It can be defined in an XML file with the <code><shape></code> element. For more* information, see the guide to <a* href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.</p>** @attr ref android.R.styleable#GradientDrawable_visible* @attr ref android.R.styleable#GradientDrawable_shape* @attr ref android.R.styleable#GradientDrawable_innerRadiusRatio* @attr ref android.R.styleable#GradientDrawable_innerRadius* @attr ref android.R.styleable#GradientDrawable_thicknessRatio* @attr ref android.R.styleable#GradientDrawable_thickness* @attr ref android.R.styleable#GradientDrawable_useLevel* @attr ref android.R.styleable#GradientDrawableSize_width* @attr ref android.R.styleable#GradientDrawableSize_height* @attr ref android.R.styleable#GradientDrawableGradient_startColor* @attr ref android.R.styleable#GradientDrawableGradient_centerColor* @attr ref android.R.styleable#GradientDrawableGradient_endColor* @attr ref android.R.styleable#GradientDrawableGradient_useLevel* @attr ref android.R.styleable#GradientDrawableGradient_angle* @attr ref android.R.styleable#GradientDrawableGradient_type* @attr ref android.R.styleable#GradientDrawableGradient_centerX* @attr ref android.R.styleable#GradientDrawableGradient_centerY* @attr ref android.R.styleable#GradientDrawableGradient_gradientRadius* @attr ref android.R.styleable#GradientDrawableSolid_color* @attr ref android.R.styleable#GradientDrawableStroke_width* @attr ref android.R.styleable#GradientDrawableStroke_color* @attr ref android.R.styleable#GradientDrawableStroke_dashWidth* @attr ref android.R.styleable#GradientDrawableStroke_dashGap* @attr ref android.R.styleable#GradientDrawablePadding_left* @attr ref android.R.styleable#GradientDrawablePadding_top* @attr ref android.R.styleable#GradientDrawablePadding_right* @attr ref android.R.styleable#GradientDrawablePadding_bottom*/
public class GradientDrawable extends Drawable {....
}
修改solid颜色
在源码中找到和solid颜色相关的代码
- 1.XML中属性解析
<solid android:color="@color/red"/>
结合源码开头的注释,可以看到对应的的styleable属性为:GradientDrawableSolid_color - 2.整个文件检索相关方法
检索 GradientDrawableSolid_color
发现在updateGradientDrawableSolid
方法中解析并使用
并且最终调用了setColor
方法 - 3.查看setColor相关源码
有两处相关,
分别是:
setColor(@ColorInt int argb)
setColor(@Nullable ColorStateList colorStateList)
从源码可见,二者实现逻辑基本一致(详见下方源码)
并且从方法注释解读确认确实是需要找的填充色。 - 4.确认最终实现方式
修改Solid颜色调用setColor方法即可。
参数可选ColorInt 或者 ColorStateList均可。
package android.graphics.drawable;import .../*** ...* @attr ref android.R.styleable#GradientDrawableSolid_color* ...*/
public class GradientDrawable extends Drawable {....private void updateGradientDrawableSolid(TypedArray a) {final GradientState st = mGradientState;// Account for any configuration changes.st.mChangingConfigurations |= a.getChangingConfigurations();// Extract the theme attributes, if any.st.mAttrSolid = a.extractThemeAttrs();// 从xml中获取Soild Color颜色final ColorStateList colorStateList = a.getColorStateList(R.styleable.GradientDrawableSolid_color);if (colorStateList != null) {setColor(colorStateList);}}..../*** Changes this drawable to use a single color instead of a gradient.* <p>* <strong>Note</strong>: changing color will affect all instances of a* drawable loaded from a resource. It is recommended to invoke* {@link #mutate()} before changing the color.** @param argb The color used to fill the shape** @see #mutate()* @see #setColors(int[])* @see #getColor*/public void setColor(@ColorInt int argb) {mGradientState.setSolidColors(ColorStateList.valueOf(argb));mFillPaint.setColor(argb);invalidateSelf();}/*** Changes this drawable to use a single color state list instead of a* gradient. Calling this method with a null argument will clear the color* and is equivalent to calling {@link #setColor(int)} with the argument* {@link Color#TRANSPARENT}.* <p>* <strong>Note</strong>: changing color will affect all instances of a* drawable loaded from a resource. It is recommended to invoke* {@link #mutate()} before changing the color.</p>** @param colorStateList The color state list used to fill the shape** @see #mutate()* @see #getColor*/public void setColor(@Nullable ColorStateList colorStateList) {mGradientState.setSolidColors(colorStateList);final int color;if (colorStateList == null) {color = Color.TRANSPARENT;} else {final int[] stateSet = getState();color = colorStateList.getColorForState(stateSet, 0);}mFillPaint.setColor(color);invalidateSelf();}/*** Returns the color state list used to fill the shape, or {@code null} if* the shape is filled with a gradient or has no fill color.** @return the color state list used to fill this gradient, or {@code null}** @see #setColor(int)* @see #setColor(ColorStateList)*/@Nullablepublic ColorStateList getColor() {return mGradientState.mSolidColors;}
}
修改Stroke颜色
跟Solid一样的方式,在源码中找到和Stroke颜色相关的代码
- 1.XML中的属性解析
<stroke android:color="@color/black"/>
结合源码开头的注释,可以看到对应的的styleable属性为:GradientDrawableStroke_color - 2.整个文件检索相关方法
检索 GradientDrawableStroke_color
发现在updateGradientDrawableStroke
方法中解析并使用
并且最终调用了setStroke
方法 - 3.查看setStroke相关源码
有四处多态相关,
分别是:
setStroke(int width, @ColorInt int color)
setStroke(int width, ColorStateList colorStateList)
setStroke(int width, @ColorInt int color, float dashWidth, float dashGap)
setStroke(int width, ColorStateList colorStateList, float dashWidth, float dashGap)
这个和Solid的颜色方式一样,
从源码可见,实现逻辑基本一致(详见下方源码) - 4.确认最终实现方式
修改Stroke颜色调用setStroke方法即可。但是可能需要单独再次计算一次width。
package android.graphics.drawable;import .../*** ...* @attr ref android.R.styleable#GradientDrawableStroke_color* ...*/
public class GradientDrawable extends Drawable {....private void updateGradientDrawableStroke(TypedArray a) {final GradientState st = mGradientState;// Account for any configuration changes.st.mChangingConfigurations |= a.getChangingConfigurations();// Extract the theme attributes, if any.st.mAttrStroke = a.extractThemeAttrs();// We have an explicit stroke defined, so the default stroke width// must be at least 0 or the current stroke width.final int defaultStrokeWidth = Math.max(0, st.mStrokeWidth);final int width = a.getDimensionPixelSize(R.styleable.GradientDrawableStroke_width, defaultStrokeWidth);final float dashWidth = a.getDimension(R.styleable.GradientDrawableStroke_dashWidth, st.mStrokeDashWidth);ColorStateList colorStateList = a.getColorStateList(R.styleable.GradientDrawableStroke_color);if (colorStateList == null) {colorStateList = st.mStrokeColors;}if (dashWidth != 0.0f) {final float dashGap = a.getDimension(R.styleable.GradientDrawableStroke_dashGap, st.mStrokeDashGap);setStroke(width, colorStateList, dashWidth, dashGap);} else {setStroke(width, colorStateList);}}..../*** <p>Set the stroke width and color for the drawable. If width is zero,* then no stroke is drawn.</p>* <p><strong>Note</strong>: changing this property will affect all instances* of a drawable loaded from a resource. It is recommended to invoke* {@link #mutate()} before changing this property.</p>** @param width The width in pixels of the stroke* @param color The color of the stroke** @see #mutate()* @see #setStroke(int, int, float, float)*/public void setStroke(int width, @ColorInt int color) {setStroke(width, color, 0, 0);}/*** <p>Set the stroke width and color state list for the drawable. If width* is zero, then no stroke is drawn.</p>* <p><strong>Note</strong>: changing this property will affect all instances* of a drawable loaded from a resource. It is recommended to invoke* {@link #mutate()} before changing this property.</p>** @param width The width in pixels of the stroke* @param colorStateList The color state list of the stroke** @see #mutate()* @see #setStroke(int, ColorStateList, float, float)*/public void setStroke(int width, ColorStateList colorStateList) {setStroke(width, colorStateList, 0, 0);}/*** <p>Set the stroke width and color for the drawable. If width is zero,* then no stroke is drawn. This method can also be used to dash the stroke.</p>* <p><strong>Note</strong>: changing this property will affect all instances* of a drawable loaded from a resource. It is recommended to invoke* {@link #mutate()} before changing this property.</p>** @param width The width in pixels of the stroke* @param color The color of the stroke* @param dashWidth The length in pixels of the dashes, set to 0 to disable dashes* @param dashGap The gap in pixels between dashes** @see #mutate()* @see #setStroke(int, int)*/public void setStroke(int width, @ColorInt int color, float dashWidth, float dashGap) {mGradientState.setStroke(width, ColorStateList.valueOf(color), dashWidth, dashGap);setStrokeInternal(width, color, dashWidth, dashGap);}/*** <p>Set the stroke width and color state list for the drawable. If width* is zero, then no stroke is drawn. This method can also be used to dash* the stroke.</p>* <p><strong>Note</strong>: changing this property will affect all instances* of a drawable loaded from a resource. It is recommended to invoke* {@link #mutate()} before changing this property.</p>** @param width The width in pixels of the stroke* @param colorStateList The color state list of the stroke* @param dashWidth The length in pixels of the dashes, set to 0 to disable dashes* @param dashGap The gap in pixels between dashes** @see #mutate()* @see #setStroke(int, ColorStateList)*/public void setStroke(int width, ColorStateList colorStateList, float dashWidth, float dashGap) {mGradientState.setStroke(width, colorStateList, dashWidth, dashGap);final int color;if (colorStateList == null) {color = Color.TRANSPARENT;} else {final int[] stateSet = getState();color = colorStateList.getColorForState(stateSet, 0);}setStrokeInternal(width, color, dashWidth, dashGap);}}
结语
还有其它的相关属性都可以根据源码中的实现和开放的api进行操作。
不再一一列举,熟读源码即可。
或者参考文章尾部的官方Api文档。
参考文献
https://developer.android.google.cn/reference/android/graphics/drawable/GradientDrawable
Android shape动态修改颜色相关推荐
- Android怎么动态修改vector填充颜色?
android怎么动态修改vector填充颜色? 要动态修改Android中的矢量图形(Vector)填充颜色,可以按照以下步骤: 在您的布局文件中,添加一个 ImageView,并设置其 src 属 ...
- 修改sim卡号码 android,android 如何动态修改SIM卡应用名称 MT6572 MT6589
两种方法: 方法1: packages\apps\launcher2\src\com\android\launcher2\PagedViewIcon.java 1:6575.6573.6577平台: ...
- android shape 无边框颜色,Android 使用shape定义不同控件的的颜色、背景色、边框色...
Android 使用shape定义不同控件的的颜色.背景色.边框色 设置按钮的右边框和底边框颜色为红色,边框大小为3dp: 在drawable新建一个 buttonstyle.xml的文件,内容如下: ...
- android动态更新配置文件,Android如何动态修改Manifest文件
修改manifest文件Android Manifest.xml,添加相应的声明.在这里,我们需要将新定义的活动PrefsActivity注册到manifest文件. 同前面一样,在Eclipse中打 ...
- Android运行时修改Manifest,Android如何动态修改Manifest文件
慕妹3242003 修改manifest文件Android Manifest.xml,添加相应的声明.在这里,我们需要将新定义的活动PrefsActivity注册到manifest文件.同前面一样,在 ...
- android 动态修改资源,Android如何动态修改Manifest文件
修改manifest文件Android Manifest.xml,添加相应的声明.在这里,我们需要将新定义的活动PrefsActivity注册到manifest文件. 同前面一样,在Eclipse中打 ...
- android 输入光标修改颜色_2.2 输入数值与文本
用户可直接选择(无需在单元格中双击插入光标)某空白单元格,然后直接向单元格内输入数据或是公式,输入过程中,状态栏左下角显示为"输入"状态,数据输入完毕后按回车键<Enter& ...
- 微信小程序 动态修改颜色
在h5中可以用js根据id啊.class啊等等找到控件,然后.css 但是在小程序中没有,小程序是数据绑定的模式,style也可以这样写 1,在data中定义变量color data: {color: ...
- android 动态更改主题,Android应用动态修改主题的方法示例
1.使用API设置主题 如下所示,在Activity中使用setTheme setTheme(R.style.MyTheme1); 2.调用API的时机 需要在super.onCreate(saved ...
- 动态修改svg图片颜色
使用场景 引入颜色为纯色的svg图片时,动态修改svg图片填充颜色.引入的方式包括直接svg代码引用和img标签间接引用. 直接引用SVG 如果通过svg代码的方式引入图片,那么可以直接修改fill属 ...
最新文章
- Android10.0 Binder通信原理(七)-Framework binder示例
- Spring Boot 管理 MVC
- keymap in ubuntu
- ACM-ICPC训练行动路线图
- Mac OS X上安装 Ruby运行环境
- 一句python,一句R︱python中的字符串操作、中文乱码、NaN情况
- Hadoop——快速入门
- 基于Zigbee和LabView的无线温度采集系统
- 基础篇:6.3)形位公差-要素 Feature
- 五线舵机驱动程序_16路舵机驱动板程序使用说明
- matlab画组合立方体,matlab小程序 画立方体
- stm32驱动ili9486液晶显示屏
- windows c语言新建dos,dos命令怎么用_DOS下创建文件、文件夹
- php判断学生姓名,【PHP】百家姓姓名判断
- 蓝牙打印 设置打印样式_Android蓝牙打印机,带你真正了解各种打印格式
- dota自走棋设置上海服务器位置,Dota2自走棋怎么设置国服 让你轻松进入国服
- 关于WPC无线充QI认证的发展
- elementUI上传图片后删除
- 159. 至多包含两个不同字符的最长子串
- 移位运算,移位操作应用