天天看點

3.0之後在LinearLayout裡增加分割線

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>      
3.0之後在LinearLayout裡增加分割線

如果我們想要很簡單的給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.三個按鈕的時候

3.0之後在LinearLayout裡增加分割線

2.兩個按鈕的時候

3.0之後在LinearLayout裡增加分割線

用了上述的方法後,每次的布局間距都會是一緻的了。

參考自:

http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0105/2268.html

http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0105/2266.html