背景

平时我们在开发中做分割线是非常频繁的事情,这里总结一下水平、垂直的实线、虚线的常见做法。对于垂直虚线给出了比较靠谱的解决方法。

水平、垂直实线

1 若是在 LineayLayout 中需要添加分割线,可以在布局文件中使用如下两个属性:

1
2
android:divider="@drawable"
android:showDividers = "middle|end|beginning|none"
  • android:divider:可以是图片文件,也可以是 xml 绘制的 shape。
  • android:showDividers:
    • middle 在每一项中间添加分割线
    • end 在整体的最后一项添加分割线
    • beginning 在整体的最上方添加分割线
    • none 无

2 在每一项之间添加一个 view,设置宽高、背景。

3 对每一项设置带有下划线的背景。一般用 shape 去做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/alLineColor" />
<size android:height="1px"/>
</shape>
</item>
<item android:bottom="1px">
<shape>
<solid android:color="@color/alWhiteColor" />
</shape>
</item>
</layer-list>

4 使用 ListView 默认的 divider,或者设置 android:divider。

水平虚线

用 shape:

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<stroke
android:width="1dp"
android:dashGap="5dp"
android:dashWidth="10dp"
android:color="#63a219" />
</shape>

width 指横线的高度,dashGap 指间隔宽度,dashWidth 指每个破折线的长度。

垂直虚线

本来想根据水平虚线的做法,使用 rotate 标签旋转 90 度。但是在实际使用中虚线的宽高并不能很好的自定义。最后还是自定义 view 来做,支持在布局文件中指定宽高、margin。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class VerticalDashView extends View {

private Paint paint;

public VerticalDashView(Context context) {
super(context);
}

public VerticalDashView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public VerticalDashView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
paint.setStrokeWidth(widthSize);

super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(getResources().getColor(R.color.brokerLightLightGrayColor));
setLayerType(LAYER_TYPE_SOFTWARE, paint);
PathEffect effects = new DashPathEffect(new float[]{10, 10}, 1);
paint.setPathEffect(effects);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawLine(0, getTop(), 0, getBottom(), paint);
}
}

ps:水平、垂直虚线在 3.0 以上要正确显示的话,需要在 AndroidManifest.xml 中关闭硬件加速:android:hardwareAccelerated=”false”。或者 view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)