Использование пользовательского представления в качестве элемента в RecyclerView - макет ограничения не может обрабатывать дочерние элементы с шириной ограничения соответствия - PullRequest
0 голосов
/ 08 февраля 2019

У меня есть 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>

Когда myTextView2 имеет ширину wrap_content, все хорошо.Но когда я делаю это 0dp, все адские разрывы освобождаются.

Проблема возникает только во втором TextView - первый TextView может иметь ширину wrap_content или 0dp, и оба работают должным образом.Но когда второй TextView имеет ширину 0dp, возникают различные проблемы:

myTextView: wrap_content, myTextView1: wrap_content - без проблем

myTextView: 0dp, myTextView1: wrap_content - без проблем

myTextView: 0dp, myTextView1: 0dp - элементы не отображаются, бесконечная прокрутка

myTextView: wrap_content, myTextView1: 0dp - myTextView отображается в виде небольшого столбца в левой части экрана, остальная часть ширины равнапусто

Есть ли исправления?

Ответы [ 3 ]

0 голосов
/ 08 февраля 2019

Я протестировал ваш макет и воспроизвел вашу проблему: мое решение, надеюсь, оно сработает: когда вы надуваете макет элемента вьюверника в onCreateViewHolder, измените null на parent в качестве второго параметра override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewHolder { val rootView = inflater.inflate(R.layout.item_temp_recyclerview, parent, false) return RvViewHolder(rootView) }

java_version:

public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
            View itemView = layoutInflater.inflate(R.layout.recyclerview_item_layout, parent, false);
            return new ViewHolder(itemView);
        }

тогда вы можете установить ширину обоих дочерних представлений на 0dp

. Совет: когда вы устанавливаете ширину для match_constraint или 0dp, вам не нужно app:layout_constraintHorizontal_bias

0 голосов
/ 13 февраля 2019

Проблема возникла из-за того, что я использовал нестандартное представление вместо раздувания макета.Решение состоит в том, чтобы программно указать ограничения макета в 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);
}
0 голосов
/ 08 февраля 2019

Попробуйте это

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="TextView" />
</android.support.constraint.ConstraintLayout>

Возможно, проблема в том, что вы забыли добавить app:layout_constraintBottom_toBottomOf="parent"

...