以编程方式设置 LinearLayout 分隔线大小

Programmatically setting LinearLayout divider size

我已经尝试了多种解决方案,但 none 似乎有效!我目前正在使用以下 Drawable 作为分隔线(这是水平示例,但同样的方法也适用于垂直,将高度切换为宽度)。

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

分隔线看起来像这样:

<?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>

但是我希望能够以编程方式设置分隔线大小,因为直到运行时我才知道大小应该是多少。我试过像这样创建 ShapeDrawable

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);

但是分隔线没有出现,项目只是粘在一起。我很确定这不是像素密度问题,因为我输入的任何数字都会得到相同的效果 - 就好像可绘制对象实际上并没有采用我设置的大小。

您的可绘制高度为 0。请尝试以下操作:

<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>

或添加:

drawable.setIntrinsicHeight(height);