Search code examples
androidandroid-linearlayoutnine-patch

Change the color of divider in LinearLayout


May I know how I can change the color of divider in LinearLayout?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal"
    android:divider="?android:attr/dividerVertical"
    android:dividerPadding="12dip"
    android:showDividers="middle"
    android:background="#ff2d2d2d" >
...
</LinearLayout>

Do I need to manually copy 9 patch image from Android SDK into my project, and define my own attribute to refer it?


Solution

  • It looks like android:divider attribute doesn't accept a color value. So you have to create a separate divider drawable in order to get it works:

    divider.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
    
        <size android:width="1dip" />
        <solid android:color="#f00" />
    
    </shape>
    

    layout.xml

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal"
        android:divider="@drawable/divider"
        android:dividerPadding="12dip"
        android:showDividers="middle"
        android:background="#ff2d2d2d" >
    

    Also, please note that android:divider is only available in android 3.0 or higher and it doesn't work in previous android versions.