Android史上最强分割线全攻略

本文详细探讨了在Android中实现分割线的各种方法及其优缺点,包括LinearLayout的divider属性、自定义控件、RecyclerView的ItemDecoration。通过实例代码,展示了在不同场景下如何高效、灵活地实现分割线,避免过度绘制和代码冗余,帮助开发者更好地解决这一常见但棘手的问题。
摘要由CSDN通过智能技术生成

借鉴自

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" 
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值