優(yōu)雅的給LinearLayout設(shè)置分割線
LinearLayout是我們使用很頻繁的一個(gè)容器,而且大多數(shù)情況下我們需要給LinearLayout下面的child設(shè)置分割線或者設(shè)置相應(yīng)的間距。
一般來(lái)說(shuō)我們首先想到的是在child前后添加分割線的View和setMargin值來(lái)實(shí)現(xiàn)。這種方法雖然可以實(shí)現(xiàn)當(dāng)前的效果,但是感覺(jué)實(shí)現(xiàn)起來(lái)麻煩,特別是當(dāng)某個(gè)child需要隱藏的時(shí)候,我們還需要隱藏分割線,對(duì)于用margin設(shè)置間距的情況下,還可能出現(xiàn)ui顯示異常。
其實(shí)LinearLayout有個(gè)divider屬性就是用來(lái)設(shè)置分割線的,Android提供三種方式設(shè)置分割線
- SHOW_DIVIDER_BEGINNING //LinearLayout頭部添加
- SHOW_DIVIDER_MIDDLE //LinearLayout中間添加(即各child之間添加)
- SHOW_DIVIDER_END //LinearLayout底部添加
xml實(shí)現(xiàn)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@drawable/divider"
android:showDividers="middle">
<View
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<View
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
代碼實(shí)現(xiàn)當(dāng)然也可以在LinearLayout中找到相應(yīng)的代碼進(jìn)行設(shè)置
public void setDividerDrawable(Drawable divider);
public void setShowDividers(@DividerMode int showDividers);
用divider設(shè)置分割線,方便快捷還不會(huì)因?yàn)槿鄙倌硞€(gè)child帶來(lái)意想不到的ui上的bug。