Android开发中如何设置View高度使其占满图片下方全部剩余区域
问题根因
你当前遇到的色块View不可见问题,是因为RelativeLayout在自身高度为wrap_content的前提下,子View设置android:layout_height="match_parent"会触发测量逻辑异常:系统测量子View时还未计算出RelativeLayout本身的总高度,会直接给子View赋值高度为0,所以看不到色块。
解决方案
最简单的适配方法不需要修改现有布局结构,只需要给colorBar新增两个对齐属性,让它同时贴住RelativeLayout的顶部和底部,即可自动撑满整个父容器高度:
<View android:layout_width="3dp" android:layout_height="match_parent" android:id="@+id/colorBar" android:background="@color/grad_23" android:layout_alignParentStart="true" <!-- 新增以下两个属性 --> android:layout_alignParentTop="true" android:layout_alignParentBottom="true" />
修改后可以删除原有的android:minHeight="50dp"、android:layout_centerVertical="true"、android:layout_gravity="start"冗余属性,色块就会自动适配图片下方所有区域的高度,跟随下方文本内容的高度自动变化。
替代方案(LinearLayout实现)
如果想要用LinearLayout配合权重实现,也可以按如下结构调整:
- 把原有的
RelativeLayout替换为水平方向的LinearLayout,高度设为wrap_content - 第一个子View为
colorBar,高度设为match_parent,宽度3dp - 第二个子View为垂直方向的
LinearLayout,宽度match_parent,高度wrap_content,存放四个TextView
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <View android:id="@+id/colorBar" android:layout_width="3dp" android:layout_height="match_parent" android:background="@color/grad_23"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- 这里放tvTitle、tvWebLink、tvDesc、tvDateTime四个TextView --> </LinearLayout> </LinearLayout>
内容的提问来源于stack exchange,提问作者user16482035
相关产品推荐
相关产品推荐

