使用自定义视图作为 RecyclerView 中的项目 - 约束布局无法处理具有匹配约束宽度的子项

Luk*_*uke 2 android android-recyclerview android-constraintlayout

我有一个RecyclerView,其中项目视图是通过在自定义视图中膨胀布局来创建的ConstraintLayout,其根为 。

当我将子视图设置为具有宽度时,wrap_content它工作正常。

但是当我将第二个子视图设置为具有宽度0dp(“match_constraint”)时,奇怪的事情发生了。

这是我的项目布局:

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="wrap_content"
>

<TextView
    android:id="@+id/myTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="TextView"
    />

<TextView
    android:id="@+id/myTextView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:textColor="@color/text_color_dark_primary"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/myTextView"
    tools:text="TextView"
    />

</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

当 myTextView2 有 width 时wrap_content,一切都很好。但是当我成功时0dp,所有的地狱都崩溃了。

该问题仅发生在第二个 TextView 上 - 第一个 TextView 可以具有宽度wrap_content或0dp,并且都按预期工作。但是当第二个 TextView 有 width 时0dp,就会出现不同的问题:

myTextView: wrap_content, myTextView1: wrap_content - 没问题

myTextView: 0dp, myTextView1: wrap_content - 没问题

myTextView: 0dp, myTextView1: 0dp - 无项目显示,无限滚动

myTextView: wrap_content, myTextView1: 0dp - myTextView 显示为屏幕左侧的小列,其余宽度为空白

有任何修复吗?

Luk*_*uke 7

问题出现是因为我使用的是自定义视图,而不是膨胀布局。解决方案是以编程方式在 中指定布局约束onCreateViewHolder,如下所述:https : //stackoverflow.com/a/48123513/6007104

具体来说:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // no need for a LayoutInflater instance—
    // the custom view inflates itself
    CustomView itemView = new CustomView(parent.getContext());
    // manually set the CustomView's size - this is what I was missing
    itemView.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
    ));
    return new ViewHolder(itemView);
}
Run Code Online (Sandbox Code Playgroud)