Создание настраиваемых элементов RecyclerView - PullRequest
0 голосов
/ 11 марта 2020

У меня есть RecyclerView, ограниченный родителем слева и справа. Есть два столбца, и я добавил пространство между ними. Между строками есть дополнительное пространство, которое должно быть таким же, как между столбцами. Проблема в том, что android экраны телефонов различаются по размеру, и я хочу, чтобы моя компоновка ViewHolder подстраивалась под это, сохраняя одинаковое пространство между столбцами и строками. Как мне этого добиться?

Вот мой макет элемента:

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>

        <variable
            name="business"
            type="me.robotcode.svezazene.model.Business" />

        <variable
            name="listener"
            type="me.robotcode.svezazene.view.BusinessClickListener" />


    </data>

    <androidx.constraintlayout.widget.ConstraintLayout

        android:layout_width="170dp"
        android:layout_height="230dp"
        android:background="@color/white"
        android:onClick="@{listener::onBusinessClicked}">

        <ImageView
            android:id="@+id/business_item_image"
            android:layout_width="fill_parent"
            android:layout_height="150dp"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:imageUrl="@{business.gallery.images.images[0]}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:srcCompat="@drawable/services_test" />

        <TextView
            android:id="@+id/business_item_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:fontFamily="@font/roboto_regular"
            android:textColor="#7983AB"
            android:textSize="12sp"
            android:text="@{business.city}"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/business_item_image"
            tools:text="Kolašin" />

        <TextView
            android:id="@+id/business_item_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="6dp"
            android:layout_marginEnd="10dp"
            android:text="@{business.title}"
            android:fontFamily="@font/roboto_bold"
            android:textColor="#5A270C"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/business_item_location"
            app:layout_constraintTop_toBottomOf="@+id/business_item_location"
            tools:text="Far far away, behind the word mountains" />

        <ImageView
            android:id="@+id/business_item_liked"
            android:layout_width="29dp"
            android:layout_height="29dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="65dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            tools:srcCompat="@drawable/save_1" />

        <TextView
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:id="@+id/businessId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="@{String.valueOf(business.id)}"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Инициализация моего адаптера:

    businessList.apply {
        val spanCount = 2
        this.layoutManager = GridLayoutManager(context, spanCount)
        this.adapter = businessListAdapter
        this.addItemDecoration(GridSpacingItemDecoration(spanCount,resources.getDimension(15dp, false))
        this.isNestedScrollingEnabled = false
            }

Я написал 15dp, чтобы сделать код чище, на самом деле это R.dimen.default_padding).toInt(). Класс, который добавляет это пространство:

    class GridSpacingItemDecoration(
        private val spanCount: Int,
        private val spacing: Int,
        private val includeEdge: Boolean) : 
        ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: 
            RecyclerView.State) {
            val position = parent.getChildAdapterPosition(view) 
            val column = position % spanCount...
            else {
                outRect.left = column * spacing / spanCount
                outRect.right =
                    spacing - (column + 1) * spacing / spanCount
                if (position >= spanCount) {
                    outRect.top = spacing
                }
            }
        }

    }

Я добавил ... , чтобы пропустить часть кода, которая добавляет ребра, поскольку я не использую в этом адаптере. Теперь RecyclerView в XML выглядит следующим образом:

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/businessList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />

Как это выглядит: Fragmment holding this particular RecyClerView Строка заголовка ограничена так же, как RecyclerView. На некоторых экранах это выглядит совершенно нормально, но на некоторых это происходит, что не является ошибкой, это код, который я написал, и понятно, что это произойдет, но я не знаю, что делать, чтобы настроить мой держатель элемента в размер.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...