Android + setDividerDrawable on LinearLayout?

I am interested in dynamically adding separators to LinearLayout. In the docs, I see that LinearLayout contains the CONST "SHOW_DIVIDER_MIDDLE" along with the get and set divider methods. Can someone show me how I implement it? Thank you

"This does not work"

xml layout:

<LinearLayout android:id="@+id/bar"
        android:orientation="horizontal" 
        android:layout_height="40dip" android:layout_width="fill_parent"
        android:background="@drawable/ab_background_gradient" android:gravity="right|center_vertical">

        <!-- sort button -->
        <Button android:id="@+id/sortBtn" android:background="@drawable/defaultt"
                android:layout_width="30dip" android:layout_height="30dip" android:onClick="sortThis" />

        <!-- add button -->
        <Button android:id="@+id/addBtn" android:background="@drawable/defaultt"
                android:layout_width="30dip" android:layout_height="30dip" android:onClick="addThis" />
    </LinearLayout>

Main:

...
private void setupViews() {
        //bar
        mBar = (LinearLayout) findViewById(R.id.bar);
        mBar.setDividerDrawable(R.drawable.divider);
}
+5
source share
1 answer

You need to convert the resource identifier that you are returning from R.drawable.dividerto a Drawable, ala object:

import android.content.res.Resources;
...

public void onCreate(Bundle savedInstanceState) {
    ...

    Resources res = this.getResources();

    LinearLayout layout = new LinearLayout(this);
    layout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING | LinearLayout.SHOW_DIVIDER_END);
    layout.setDividerDrawable(res.getDrawable(R.drawable.divider));

    ...
 }
...

It is assumed that you have a file named "divider.jpg" (or similar) in your resource directory.

+6
source

All Articles