Android Studio中ConstraintLayout约束不生效问题求解
问题根因
约束失效、IDE不提示约束属性的核心原因非常明确:MaterialCardView 继承自 FrameLayout,本身不具备解析约束布局属性的能力。
所有 app:layout_constraint* 格式的属性,只有在控件的直接父布局是 ConstraintLayout 时才会生效。你当前布局中,product_image 和 card_details 的直接父控件是最外层的 MaterialCardView,作为FrameLayout它只会按照FrameLayout的规则布局子View——默认所有子View对齐左上角堆叠,完全不会处理你写的约束规则,自然也不会在代码提示里给出约束相关的属性选项。
你给最外层MaterialCardView本身写的两个约束属性之所以看起来正常,是因为这个MaterialCardView的父布局是ConstraintLayout,它自己的约束会被上层父布局解析,和它内部的子View无关。
修复方案
只需要在MaterialCardView内部嵌套一层ConstraintLayout作为卡片内容的直接容器,把所有需要约束布局的子控件都放到这层容器里即可,修正后的核心布局代码如下:
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/product_card" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <!-- 卡片内部新增ConstraintLayout作为直接父容器,负责解析子控件约束 --> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/product_image" android:layout_width="match_parent" android:layout_height="280dp" android:scaleType="centerCrop" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="ImageContrastCheck" tools:srcCompat="@tools:sample/backgrounds/scenic" /> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/card_details" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="15dp" android:layout_marginTop="20dp" android:layout_marginEnd="15dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/product_image"> <TextView android:id="@+id/product_title" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/product_price" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/product_title" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView>
替换后重新预览布局,card_details就会按照你写的约束自动排列到product_image的下方。
内容的提问来源于stack exchange,提问作者Ahmad Nasriya
相关产品推荐
相关产品推荐

