Android开发:如何通过Java代码修改Drawable中android:dashWidth属性值
修改Layer Drawable中圆弧的dashWidth属性
嘿,我刚好碰到过类似的需求,给你一步步讲怎么解决!
首先咱们得明确:你用的layer-list对应的是Android里的LayerDrawable,而里面的圆弧shape对应的是GradientDrawable——这俩类型转换是关键。因为GradientDrawable没有单独的setDashWidth方法,得通过setStroke()来一次性设置线条宽度、颜色、虚线宽度和间距。
先补全你的Drawable示例(方便对应代码)
假设你的XML大概是这样的(你贴的代码没写完,我补个常见的圆弧虚线示例):
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="arc" android:innerRadiusRatio="2.5" android:thicknessRatio="8" android:useLevel="false"> <stroke android:width="4dp" android:color="#FF4081" android:dashWidth="8dp" android:dashGap="4dp"/> </shape> </item> </layer-list>
具体Java代码实现
假设你把这个Drawable设置给了一个ImageView(id为iv_arc),或者作为某个View的背景,代码如下:
// 1. 获取LayerDrawable对象 // 如果是ImageView用getDrawable(),如果是背景用getBackground() LayerDrawable layerDrawable = (LayerDrawable) findViewById(R.id.iv_arc).getDrawable(); // 2. 拿到layer-list里对应圆弧的那个Drawable(这里是第0个item,根据你的XML调整索引) GradientDrawable arcDrawable = (GradientDrawable) layerDrawable.getDrawable(0); // 3. 把dp转成像素值(Android代码里尺寸要用像素,不能直接用dp) float density = getResources().getDisplayMetrics().density; int newDashWidth = (int) (16 * density); // 比如要改成16dp的虚线宽度 int strokeWidth = (int) (4 * density); // 保持原来的线条宽度,也可以改 int strokeColor = getResources().getColor(R.color.your_stroke_color); // 原线条颜色 int dashGap = (int) (4 * density); // 原虚线间距,也可以修改 // 4. 调用setStroke方法更新属性,参数依次是:线条宽度、颜色、虚线宽度、虚线间距 arcDrawable.setStroke(strokeWidth, strokeColor, newDashWidth, dashGap); // 5. 通知Drawable刷新显示 arcDrawable.invalidateSelf();
几个注意点
- 一定要确认类型转换正确:如果你的shape不是用
<shape>标签写的,而是其他类型(比如自定义Drawable),那得对应调整转换的类。但XML里的<shape arc>肯定是GradientDrawable。 - 如果你的Drawable是作为View的背景,记得把
getDrawable()换成getBackground()。 - 为什么之前搜不到相关方案?因为这个属性不能单独修改,必须通过
setStroke()批量设置线条相关属性,很多人不知道这一点,只会搜单独的setDashWidth方法,自然找不到。
内容的提问来源于stack exchange,提问作者RagAnt
相关产品推荐
相关产品推荐

