Android 實現分割線的幾種方式

最近項目的UI除了圖標是美工做的,其他的都要自己代碼實現。所以導致最近創建的drawable資源(selector、layer-list、shape等等)文件特別多。

在這裏總結幾種實現分割線的方式:

1、使用layer-list實現:

(1)頂部黑色分割線、白色背景

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/black"/>
    <item android:left="1dp" android:top="1dp" android:right="1dp" android:drawable="@android:color/white"/>
</layer-list>
(2)左邊上邊右邊黑色分割線、白色背景

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/black"/>
    <item android:left="1dp" android:top="1dp" android:right="1dp" android:drawable="@android:color/white"/>
</layer-list>
layer-list使用總結:沒有佈局限制,只要是View都有可以通過background設置實現,而且不會干擾到佈局,比較通用,我們現在項目用得最多的就是用這種方式實現的。這裏有兩點需要注意的地方:

第一、當你的背景要設置透明的時候並且需要有邊框的時候,這種方式就不適用了。

第二、item標籤的width和height屬性是API 23(Android 6.0)新增的,對於API23以下的手機是不兼容的,不會報錯,但是width和height屬性值不起作用。

2、LinearLayout的divider屬性:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.cqz.divider.LayerListDividerActivity"
    android:background="@android:color/darker_gray"
    android:padding="16dp"
    android:showDividers="middle"
    android:divider="@drawable/div_linealayout_8dp_transparent"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/div_top_black_border_while_solid"
        android:text="top border "
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/div_left_top_right_black_border_while_solid"
        android:text="left top right border "
        />

</LinearLayout>

以上佈局的實現效果:


LinearLayout的divider使用總結:使用場景比較侷限,針對LinearLayout纔有,記得設置showDividers屬性,其中

middle表示分割線顯示在佈局子元素的中間,條數=佈局子元素數量-1。

beginning表示分割線顯示在佈局的起始位置,只會畫一條。

end表示分割線顯示在佈局結束位置,只會畫一條。

還有shape資源的size屬性記得設置。

3、直接用View去實現

具體怎麼用相信大家都知道了,總結一下:這種實現方式需要修改佈局,不夠優雅。一般在前兩種方式無法實現的情況下才使用。這種實現方式可以實現所有佈局分割線。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章