如何在LinearLayout中添加分割线,就像下面这张图一样。
推荐方法:
LinearLayout有两个属性
1、divider
android:divider = ""
- divider可以是图片文件,也可以是xml绘制的shape。
- 使用shape的时候一定要添加
<size>
,一定要添加color
,即使是透明也要写上
例如:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/black" />
<size android:height="1px" />
</shape>
2、showDividers
android:showDividers = "middle|end|beginning|none"
- middle 在每一项中间添加分割线
- end 在整体的最后一项添加分割线
- beginning 在整体的最上方添加分割线
- none 无
添加上这两个属性就可以实现图中效果。
但是,这种属性只有Android3.0
以上才支持。
兼容3.0以下版本,需要引用android-support-v7-appcompat.jar
使用android.support.v7.widget.LinearLayoutCompat
,用法和LinearLayout
一样。但是再设置属性的时候需要使用设置xml命名空间
比如
xmlns:app="http://schemas.android.com/apk/res-auto"
app:divider=""
app:showDividers=""
LinearLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:divider="@drawable/divider"
android:showDividers="middle"></LinearLayout>
LinearLayout
<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:divider="@drawable/divider"
app:showDividers="middle"></android.support.v7.widget.LinearLayoutCompat>
其他方法一:
在每一项中间添加一个View,设置view的宽高,和背景。(不推荐,浪费资源)
其他方法二:
给每一项添加带有下划线的背景。(不推荐,麻烦)