【问题标题】:Programmatically setting LinearLayout divider size以编程方式设置 LinearLayout 分隔线大小
【发布时间】:2017-12-06 18:09:35
【问题描述】:

我已经尝试了多种解决方案,但似乎都没有奏效!我目前正在使用以下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);

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

【问题讨论】:

    标签: android android-linearlayout android-drawable divider


    【解决方案1】:

    您的可绘制高度为 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);
    

    【讨论】:

    • 第一种方法可以正常工作,即使在 xml 中将高度设置为 0。由于某种原因,使用ShapeDrawable 需要同时设置IntrinsicHeightIntrinsicWidth
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多