借鉴自
https://blog.csdn.net/megatronkings/article/details/52156312
说实话,分割线这个东西,真的太难太难了!!!
难在何处?难在用最对的方式去实现它!
1.view——管理代码不便,绘制开销大。非常非常不好
2.图片——修改不便,增加apk体积。非常非常不好
3.Java代码——使用不便,增加代码量。非常非常不好
4.layer-list通过覆盖实现——过度绘制,修改不便。非常非常不好
5.shape——设置成background会自动填充,无法实现!
6.自定义控件——做模块化的时候,需要移植这个库。不太好
7.不充满的底部分割线的这种情况,实现起来更难——又一限制条件
所以他难
本人在探索了2个小时后,终于得出了结论
1.LinearLayout——虽然background这个属性会自动填充,不能用,但是他有divider属性!
2.其他布局——自定义控件
3.RecyclerView——ItemDecoration
下面我将给出这些情况的代码,你可以直接拷去用。
代码原理就不解释了,太简单了。有问题留言。
LinearLayout充满的底部分割线(其他方向的分割线也一样)
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <size android:height="1dp"/> <solid android:color="@color/colorAccent"/> </shape>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="@drawable/line_bottom" android:showDividers="end" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools">
效果
LinearLayout不充满的底部分割线
<?xml version="1.0" encoding="utf-8"?> <inset xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/line_bottom" android:insetLeft="15dp"> </inset>
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <size android:height="1dp"/> <solid android:color="@color/colorAccent"/> </shape>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="@drawable/line_bottom_not_full" android:showDividers="end" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools">
效果
其他布局:网上开源库很多,不过我不太喜欢用别人的库,所以自己实现了一个(实现了主流的RelativeLayout和FrameLayout)
attrs
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="BorderRelativeLayout"> <attr name="margin_start" format="dimension"/>线到起始端的margin <attr name="margin_end" format="dimension"/>线到末端的margin <attr name="width" format="dimension"/>线的宽度