Search code examples
androidandroid-linearlayoutandroid-drawabledivider

Programmatically setting LinearLayout divider size


I have tried multiple solutions to this but none seem to work! I am currently using the following Drawable as a divider (this is the horizontal example but the same approach works for vertical too, switching height for width).

LinearLayout linearLayout; // set with findViewById
linearLayout.setDividerDrawable(getResources().getDrawable(R.drawable.divider));
linearLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);

Where divider looks like this:

<?xml version="1.0" encoding="utf-8"?>   
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="10dp"
        android:height="0dp" />
</shape>

However I'd like to be able to set the divider size programatically as I don't know what the size should be until runtime. I've tried creating a ShapeDrawable like this:

int desiredWidth = 10;
LinearLayout linearLayout; // set with findViewById
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.getPaint().setColor(Color.TRANSPARENT);
shapeDrawable.setIntrinsicWidth(desiredWidth);
linearLayout.setDividerDrawable(shapeDrawable);
linearLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);

But the divider doesn't appear, and the items are just stuck together. I'm pretty sure it's not a pixel density issue as whatever number I put in I get the same effect - it's as though the drawable doesn't actually take the size I set it to.


Solution

  • your drawable height is 0. try the following:

    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <size
            android:width="10dp"
            android:height="10dp" />
         <!--android:height depends on the height you want for the horizontal line--->
    </shape>
    

    or add:

    drawable.setIntrinsicHeight(height);