Android如何实现图片布局高度适配右侧动态内容布局并设置背景色
实现方案
1 布局XML调整
你当前的布局存在两个限制自适应的问题:父容器固定高度200sp、左侧图片容器内的CardView固定120dp高度,按以下规则调整即可实现左侧高度跟随右侧内容自适应:
- 将父容器
parentContainer的android:layout_height属性从200sp改为wrap_content,让父容器高度由内容最高的子View决定 - 给左侧图片容器
store_cat_img_container添加android:layout_alignParentTop="true"和android:layout_alignParentBottom="true"属性,让它自动撑满父容器高度 - 将左侧图片外层的CardView的
android:layout_height属性从120dp改为match_parent,匹配父容器高度 - 给右侧业务布局新增id
rightContentContainer,方便后续代码获取高度
调整后的核心XML片段示例:
<RelativeLayout android:id="@+id/parentContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="@dimen/sp_5" android:layout_marginTop="@dimen/sp_10" android:layout_marginBottom="@dimen/sp_10" android:background="@drawable/top_rounded_background"> <RelativeLayout android:id="@+id/store_cat_img_container" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true"> <androidx.cardview.widget.CardView android:layout_width="150dp" android:layout_height="match_parent" android:layout_centerVertical="true" app:cardCornerRadius="@dimen/sp_10" app:cardElevation="@dimen/sp_10"> <ImageView android:id="@+id/productImage" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:adjustViewBounds="true" android:scaleType="fitXY" android:src="@mipmap/images" /> </androidx.cardview.widget.CardView> </RelativeLayout> <!-- 右侧业务布局新增id --> <RelativeLayout android:id="@+id/rightContentContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/store_cat_img_container" android:paddingLeft="@dimen/sp_10"> <!-- 原有右侧业务布局内容保持不变即可 --> </RelativeLayout> </RelativeLayout>
2 动态设置图片背景色
在业务代码中监听右侧布局的尺寸变化,拿到高度后按你的业务规则设置背景色即可,Kotlin示例代码如下:
rightContentContainer.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // 移除重复监听避免多次回调 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { rightContentContainer.viewTreeObserver.removeOnGlobalLayoutListener(this) } else { rightContentContainer.viewTreeObserver.removeGlobalOnLayoutListener(this) } // 获取右侧布局实际渲染高度 val rightHeight = rightContentContainer.measuredHeight // 按你的业务规则判断设置背景色,以下为示例逻辑 val targetBgColor = when { rightHeight > dp2px(400) -> ContextCompat.getColor(context, R.color.light_blue) rightHeight > dp2px(300) -> ContextCompat.getColor(context, R.color.light_grey) else -> ContextCompat.getColor(context, R.color.white) } productImage.setBackgroundColor(targetBgColor) } }) // dp转px工具方法,可选 private fun dp2px(dp: Int): Int { return (dp * Resources.getSystem().displayMetrics.density).toInt() }
如果是在RecyclerView Adapter中使用该布局,注意在视图复用时及时移除监听避免内存泄漏。
内容的提问来源于stack exchange,提问作者Nish Lamba
相关产品推荐
相关产品推荐

