Android adjustViewBounds配合wrap_content时ImageButton宽度收缩如何解决?
问题根因
LinearLayout设置android:layout_height="wrap_content"时,测量阶段会先逐个测量子View的尺寸,此时还未确定TextView的最终高度,ImageButton会先按照自身默认最小宽度测量,后续LinearLayout高度确定为TextView高度后,不会再重新触发ImageButton的宽度适配逻辑,因此出现宽度异常收缩的问题。
解决方案
方案1:保留LinearLayout的修改方法
给外层LinearLayout和ImageButton添加对应属性即可:
<!-- 外层LinearLayout添加baselineAligned属性 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:baselineAligned="false"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试文本"/> <!-- ImageButton添加对应适配属性 --> <ImageButton android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/你的图标资源" android:adjustViewBounds="true" android:scaleType="fitCenter" android:minWidth="0dp"/> </LinearLayout>
方案2:用ConstraintLayout实现(更稳定,推荐)
通过约束直接对齐ImageButton和TextView的上下边,高度自动匹配的同时自动保留图片宽高比:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试文本" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> <ImageButton android:layout_width="wrap_content" android:layout_height="0dp" android:src="@drawable/你的图标资源" android:adjustViewBounds="true" android:scaleType="fitCenter" app:layout_constraintStart_toEndOf="@id/tv_content" app:layout_constraintTop_toTopOf="@id/tv_content" app:layout_constraintBottom_toBottomOf="@id/tv_content"/> </androidx.constraintlayout.widget.ConstraintLayout>
效果对比


内容的提问来源于stack exchange,提问作者M.Toy
相关产品推荐
相关产品推荐

