要想实现3个button线性排列并且使它们的大小相同、间隔相等、而且整体填充满整个linearlayout,我们一般的做法是在每两个button之间放一个固定宽度的view,然后设置button的宽度为0、layout_weight为1。这样虽能实现功能,可是总感觉不方便,特别是button多的时候。

 

今天介绍另一种简单、优雅的方法,就是利用android:divider属性。

1、首先新建一个固有的width/height的Drawable:

spacer_medium.xml




<?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>


2.然后设置LinearLayout的android:divider="@drawable/spacer_medium",并设置android:showDividers="middle",这样就完美解决了linearLayout的元素之间的间隔问题。



 



<LinearLayout   
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:divider="@drawable/spacer_medium"
android:background="#77000000"
android:showDividers="middle">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button"/>

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button"/>

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button"/>

</LinearLayout>