【android】巧用android:divider屬性設定LinearLayout中元素之間的間隔,

來源:互聯網
上載者:User

【android】巧用android:divider屬性設定LinearLayout中元素之間的間隔,


如,要想實現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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.