ImageView的adjustViewBounds=true属性在布局预览中渲染异常
嘿,我之前做Android布局的时候也踩过这个坑!当给ImageView加上android:adjustViewBounds="true"后,布局预览里的显示效果总是和实际运行起来对不上——要么图片被奇怪拉伸变形,要么ImageView的尺寸完全不符合预期,确实挺闹心的。
我整理了几个亲测有效的解决办法,你可以挨个试试:
检查约束布局的属性配置
这是最常见的问题根源!尤其是用ConstraintLayout的时候,要是只单独加adjustViewBounds="true",却没给ImageView设置合理的约束或宽高,预览很容易“抽风”。比如你可以把layout_width设为0dp(也就是match_constraint),配合父布局的左右约束,再把layout_height设为wrap_content,这样ImageView会自动根据图片的宽高比调整自身高度,预览也能准确显示效果。
给你个正确的代码示例参考:<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageViewCover" android:layout_width="0dp" android:layout_height="wrap_content" android:adjustViewBounds="true" android:src="@drawable/your_cover_image" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>清理布局预览缓存
Android Studio的布局预览缓存有时候会犯迷糊,哪怕你代码写得完全正确,它也会显示异常。这时候你可以点一下预览窗口右上角的“Refresh”按钮,或者直接重启Android Studio,很多时候重启后预览就恢复正常了。排查图片资源的问题
如果你的图片是.9.png格式,或者是用Vector Asset生成的矢量图,有时候预览工具会对这些特殊格式的图片识别出错。你可以先换成普通的png/jpg图片试试,看看是不是图片本身的格式问题导致了预览渲染异常。注意maxWidth/maxHeight的搭配
要是你给ImageView加了maxWidth或maxHeight属性,同时开了adjustViewBounds="true",一定要确保这些属性的数值合理——比如别把maxWidth设得比父布局还宽,不然预览里的ImageView尺寸会完全超出预期。
还有个小细节要提醒你:很多时候预览显示异常,但实际运行到手机上是正常的,这大多是Android Studio预览工具的小bug,不用太慌,按照上面的方法调整后,基本能解决预览和实际效果不一致的问题。
内容来源于stack exchange

