Android 成长在于积累和分享
本文:https://blog.csdn.net/CrazyApes/article/details/122677466
[toc]
前言
Andoid 中很多圆角或者边线的操作都喜欢用 shape 实现。
那么很多需求会用到根据特定的状态去展示当前的颜色,这个时候,可能就需要动态修改 shape 的颜色了。
当然也有小伙伴选择直接重写几个shape代表不同的状态。哈哈。
除此之外,也可以考虑使用material中的相关View实现,这个后话在说。
解决方案
答案要写在前面,分析可以后面慢慢看
修改Solid颜色
// Java
GradientDrawable shapeDrawable = (GradientDrawable) mShapeView.getBackground();
shapeDrawable.setColor(mShapeView.getResources().getColor(color));
// kotlin
val shapeDrawable = mShapeView.getBackground() 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.getBackground() 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">
<corners
android: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)
*/
@Nullable
public ColorStateList getColor() {
return mGradientState.mSolidColors;
}
}
修改Stroke颜色
跟Solid一样的方式,在源码中找到和Stroke颜色相关的代码
- XML中的属性解析
<stroke android:color="@color/black"/>
结合源码开头的注释,可以看到对应的的styleable属性为:GradientDrawableStroke_color
- XML中的属性解析
- 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方法即可。
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