CardView内ImageView圆角预览正常但真机/模拟器不显示的解决方法
解决方案
出现这个问题的核心原因是:布局预览会自动处理CardView子视图的圆角适配,但实际设备中,ImageView默认不会继承CardView的圆角裁剪规则,导致图片内容超出圆角区域。
你可以通过以下两种方式修复:
方法一:让ImageView填充CardView并开启裁剪
将ImageView的宽高设置为match_parent,同时添加android:clipToOutline="true"属性,这样图片会完全填充CardView,并且跟随CardView的圆角进行裁剪。修改后的代码如下:
<androidx.cardview.widget.CardView android:id="@+id/materialCardView2" android:layout_width="64dp" android:layout_height="64dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:cardCornerRadius="20dp" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <ImageView android:id="@+id/test_iv" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/rider" android:clipToOutline="true"/> </androidx.cardview.widget.CardView>
方法二:使用CardView的裁剪兼容属性(适用于旧版CardView)
如果你的项目使用较旧版本的CardView,可以添加app:cardPreventCornerOverlap="false"属性,让CardView的圆角直接作用于子视图:
<androidx.cardview.widget.CardView android:id="@+id/materialCardView2" android:layout_width="64dp" android:layout_height="64dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:cardCornerRadius="20dp" app:cardPreventCornerOverlap="false" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <ImageView android:id="@+id/test_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="centerCrop" android:src="@drawable/rider"/> </androidx.cardview.widget.CardView>
注意:方法一的兼容性更好,是当前推荐的解决方案。
内容的提问来源于stack exchange,提问作者Kyaw Zin
相关产品推荐
相关产品推荐

