横虚线
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
android:color="#AAAAAA"
android:dashGap="2dp"
android:dashWidth="4dp"
android:width="1dp"/>
</shape>
dashGap: 虚线间隔
dashWidth:虚线长度
width:虚线的粗细
- 把虚线的 drawable 设置为某个 View 的 background 时,需要加上
android:layerType="software"
,不然真机上只会显示实线 - View 的高度要大于虚线的 width,否则无法显示虚线
竖虚线
shape 不支持竖虚线,因此需要使用 rotate 进行旋转:
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90">
<shape android:shape="line">
<stroke
android:color="#AAAAAA"
android:dashGap="2dp"
android:dashWidth="4dp"
android:width="1dp"/>
</shape>
</rotate>
系统会先画一条横虚线再进行顺时针90°旋转,因此会有一种问题:虚线的长度跟 View 的宽度有关,因为它需要在 View 上根据宽度画出虚线,这时就决定了虚线的长度,旋转后长度也不会变化了。
有一个方法就是利用 layer-list:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:left="-300dp"
android:right="-300dp">
<rotate
android:fromDegrees="90">
<shape android:shape="line">
<stroke
android:color="#AAAAAA"
android:dashGap="2dp"
android:dashWidth="4dp"
android:width="1dp"/>
</shape>
</rotate>
</item>
</layer-list>
这里设置了 item 的偏移量,左右各 -300,这样就可以画出 -600 的竖虚线。