Programmatically setting LinearLayout divider size

杀马特。学长 韩版系。学妹 提交于 2019-12-13 03:49:48

问题


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.


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


来源:https://stackoverflow.com/questions/47680822/programmatically-setting-linearlayout-divider-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!