android:divider=
"@drawable/shape"
<!--分割线图片-->
android:showDividers=
"middle|beginning|end"
<!--分割线位置-->
分割线如果是图片那就直接使用图片就行,如果要使用颜色就必须使用shape来显示,直接使用颜色或Color是没有用的
使用shape的时候要注意设置size属性不设置宽高分割线就不会显示出来,如果使用line那填充颜色只能使用stroke来显示颜色
例子:
<LinearLayout
android:id="@+id/buttons_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@drawable/spacer_medium"
android:orientation="horizontal"
android:showDividers="middle">
<Button
android:id="@+id/btn_first"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button_1" />
<Button
android:id="@+id/btn_second"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button_2" />
<Button
android:id="@+id/btn_third"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button_3" />
</LinearLayout>
spacer_medium定义如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="@dimen/spacing_medium"
android:height="@dimen/spacing_medium" />
<solid android:color="@color/divider_color" />
</shape>

如果我们想要很简单的给linearLayout设置空隙,就不用填充颜色了。比如这样:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="@dimen/spacing_medium"
android:height="@dimen/spacing_medium" />
<solid android:color="@android:color/transparent" />
</shape>
而且在你动态改变元素的时候也不会出现bug。
这里指的bug是:
我们用传统的方式设置空隙,在显示三个按钮的时候没有问题,但在动态改变成两个按钮的时候就会出现问题。
1.三个按钮的时候
2.两个按钮的时候
用了上述的方法后,每次的布局间距都会是一致的了。
参考自:
http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0105/2268.html
http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0105/2266.html