Android XML中wrap_content/match_parent时虚线视图不显示问题求助
解决垂直虚线视图match_parent不显示的问题
问题原因
使用shape="line"创建虚线时,该类型Drawable仅能根据stroke宽度确定自身尺寸,无法随View的match_parent高度拉伸;旋转后若View无固定高度,Drawable没有足够渲染空间,导致不显示。另外原代码中solid设为白色,会遮挡虚线间隙,进一步影响显示效果。
解决方案:改用矩形Shape实现垂直虚线
替换原layer-list+rotate+line方案,用矩形Shape适配动态高度:
- 修改
res/drawable/dotted_line.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 设置固定宽度,对应虚线粗细 --> <size android:width="1dp" /> <!-- 配置虚线样式 --> <stroke android:width="1dp" android:color="#E7EBEE" android:dashWidth="3dp" android:dashGap="3dp" /> <!-- 背景设透明,避免遮挡虚线间隙 --> <solid android:color="@android:color/transparent" /> </shape>
- 调整布局中的View属性:
<View android:id="@+id/view" android:layout_width="1dp" <!-- 对应shape的宽度,确保显示竖线 --> android:layout_height="match_parent" android:background="@drawable/dotted_line" android:layerType="software" <!-- 保留该属性,避免硬件加速导致虚线失效 --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@+id/circleShape" app:layout_constraintStart_toStartOf="@+id/circleShape" app:layout_constraintTop_toBottomOf="@+id/circleShape" />
原理说明
矩形Shape会填充整个View空间,通过stroke的dashWidth和dashGap实现虚线效果,固定宽度保证虚线垂直显示,高度随View的match_parent自动拉伸,完美适配列表动态高度场景。
内容的提问来源于stack exchange,提问作者Eman Essam
相关产品推荐
相关产品推荐

