Programmatically setting LinearLayout divider size
Asked Answered
M

1

0

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.

Midvictorian answered 6/12, 2017 at 18:9 Comment(0)
P
1

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);
Pique answered 6/12, 2017 at 18:19 Comment(1)
The first approach works fine even with the height set to 0 in the xml. For some reason using the ShapeDrawable requires both IntrinsicHeight and IntrinsicWidth to be set.Midvictorian

© 2022 - 2024 — McMap. All rights reserved.