【android】巧用android:divider属性设置LinearLayout中元素之间的间隔

来源:互联网 发布:永恒纪元戒官网通知 编辑:程序博客网 时间:2024/05/01 09:51


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


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


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

spacer_medium.xml

[java] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="rectangle">  
  4.   
  5.     <size  
  6.         android:width="@dimen/spacing_medium"  
  7.         android:height="@dimen/spacing_medium" />  
  8.   
  9.     <solid android:color="@android:color/transparent" />  
  10.   
  11. </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>


参考:http://blog.csdn.net/startupmount/article/details/41745715




1 0