RecyclerView子项采用ConstraintLayout,运行时偏移问题求助
嗨,我之前也遇过这种预览正常但一跑起来RecyclerView子项就偏移的情况,结合你的代码来看,咱们可以从这几个方向入手排查:
排查自定义数据绑定属性的影响
你给pastOrderAmount用了自定义属性app:priceStringOverview="@{order.amount}",这个自定义BindingAdapter有可能在设置文本的时候不小心修改了View的布局参数(比如width或者约束关系)。建议先暂时注释掉这个属性,用普通的android:text="@{String.valueOf(order.amount)}"代替,运行看看偏移是否消失。如果问题解决了,那就是这个自定义属性的代码存在干扰布局的逻辑,得检查BindingAdapter的实现。检查RecyclerView的额外布局配置
有没有给RecyclerView添加过ItemDecoration?如果自定义了ItemDecoration的间距,可能会和子项的margin冲突导致布局计算错误。另外,还要确认Adapter的onCreateViewHolder方法里,有没有给子项View设置错误的LayoutParams(比如误用LinearLayout.LayoutParams而不是RecyclerView.LayoutParams),这也会引发布局偏移。升级ConstraintLayout版本
旧版本的ConstraintLayout偶尔会出现预览和运行时布局不一致的bug,建议把build.gradle里的ConstraintLayout依赖升级到最新稳定版,比如:implementation 'androidx.constraintlayout:constraintlayout:2.1.4'完善子项布局的约束链
你的子项里两个TextView都用了0dp(match_constraint),虽然约束看起来没问题,但可以试试给它们加上水平约束链和权重,确保宽度计算准确。修改后的布局示例如下:<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/pastorderdate" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:textColor="@color/colorPrimary" android:textSize="14sp" android:text="@{order.date}" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintHorizontal_weight="1" tools:text="2/3/2020" /> <TextView android:id="@+id/pastOrderAmount" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:textColor="@color/textColor" android:text="@{order.amount}" app:layout_constraintBottom_toBottomOf="@+id/pastorderdate" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/pastorderdate" app:layout_constraintTop_toTopOf="@+id/pastorderdate" app:layout_constraintHorizontal_weight="1" tools:text="RM50.80" /> </androidx.constraintlayout.widget.ConstraintLayout>
内容的提问来源于stack exchange,提问作者Dheeno Rao

