给TextView添加行分割线
思路:通过在TextView onDraw的方法里把行分割线画出来
自定义两个属性
<declare-styleable name="LineDividerTextView">
<attr name="line_divider" format="reference"/>
<attr name="line_divider_height" format="dimension"/>
</declare-styleable>
line_divider 分割线的drawable,可以是一个颜色,图片,只要是drawable就可以
line_divider_height 分割线的高度
画分割线
我们只需找出行与行中间的坐标即可
可以通过getLineBounds(int line, Rect bounds)这个方法获取行的边框。注意的地方是行的边框为文字加上行间距(设置了lineSpaceExtra),所以行与行中间的y坐标为
底部坐标减去 行间距的一半
onDraw代码如下
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int count = getLineCount();
for (int i = 0; i < count; i++) {
// last line not draw
if (i == count - 1) {
break;
}
getLineBounds(i, mRect);
lineDivider.setBounds(
mRect.left,
(int) (mRect.bottom - getLineSpacingExtra() / 2 - lineDividerHeight / 2),
mRect.right,
(int) (mRect.bottom - getLineSpacingExtra() / 2 + lineDividerHeight / 2));
lineDivider.draw(canvas);
}
}
然后再xml引用这个自定义view
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<etwge.yu.widget.LineDividerTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="8dp"
android:text="@string/text1"
android:textSize="16sp"
app:line_divider="@drawable/divider_gradient"
app:line_divider_height="1dp" />
<etwge.yu.widget.LineDividerTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="8dp"
android:text="@string/text2"
android:textSize="16sp"
app:line_divider="@drawable/divider_shadow"
app:line_divider_height="6dp" />
<etwge.yu.widget.LineDividerTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="8dp"
android:text="@string/text3"
android:textSize="16sp"
app:line_divider="@drawable/divider"
app:line_divider_height="6dp" />
</LinearLayout>
如图
需要注意的地方
根据line_divider_height 适当设置lineSpaceExtra的大小
行间距兼容问题
5.0以下lineSpaceExtra 会影响
到最后一行,最后一行也会有行间距,5.0以上则不会,如果需要解决这个问题,可以看我上一篇文章填填Android lineSpacingExtra 的坑