Одинаковая высота и ширина для ячеек в сетке макета Android / Kotlin - PullRequest
0 голосов
/ 28 января 2019

Как получить представление переработчика с разметкой сетки, где каждая ячейка имеет одинаковую ширину ячейки и высоту ячейки в зависимости от ширины экрана.

Я установил свой макет следующим образом

linearLayoutManager = LinearLayoutManager(this)
categoriesRecyclerView.layoutManager = GridLayoutManager(this,4)

и у меня всегда 4 ячейки подряд.

Результат выглядит следующим образом.

enter image description here

Я понимаю, почему я получил этот результат.Я устанавливаю свой контент внутри ячеек всегда на wrap_content.Поэтому, если изображение больше или текст длиннее, высота изменится.

Мой макет определяется следующим образом:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintDimensionRatio="1:1"
android:layout_margin="8dp"
android:background="@drawable/rounded_image_view">

rounded_image_view - это просто форма.

Я думал, что смогу отрегулировать расположение ограничений с помощью соотношения.

Некоторые другие вещи, которые я пробовал: использовать карты, использовать линейную разметку, поместить содержимое в View, работать с constraintHeight_percent, и я много читаю в подобных темах, как эта.Но я не нашел решения.

Полный XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintDimensionRatio="1:1"
android:layout_margin="8dp"
app:layout_constraintHeight_percent="0.5"
android:background="@drawable/rounded_image_view">

<ImageView
    android:id="@+id/categoryImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toTopOf="@id/itemTitle"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/anatomie" />

<TextView
    android:id="@+id/itemTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Anatomie"
    android:textColor="@color/colorAccent"
    android:textSize="12sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/categoryImage" />

<ImageView
    android:id="@+id/isPremiumImage"
    android:layout_width="20dp"
    android:layout_height="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/locked" />
</androidx.constraintlayout.widget.ConstraintLayout>

1 Ответ

0 голосов
/ 29 января 2019

Вы можете динамически рассчитать ширину экрана устройства и соответственно установить высоту представления элемента.

Добавьте приведенный ниже метод util для вычисления размера в свой класс адаптера.

     /**
     * calculates the size of the item based on the screen size
     */
    fun calculateSizeOfView(context: Context): Int {

        val displayMetrics = context.resources.displayMetrics
        val dpWidth = displayMetrics.widthPixels
        return (dpWidth / COLUMN_COUNT) // COLUMN_COUNT would be 4 in your case
    }

Теперь добавьте следующие строки кода внутри метода onCreateViewHolder вашего класса адаптера.

1) получите размер каждого элемента из метода util

2) создайте параметры макета - как высоту, так и ширинукак указано выше вычисленное значение

3) установить параметры для вашего завышенного представления внутри OnCreateViewHolder

val view = *your_inflated_view* // the return view of your .inflate method
val size = calculateSizeOfView(*your_context*)

val margin = 8 * 4 // any vertical spacing margin = your_margin * column_count 
val layoutParams = GridLayout.LayoutParams(ViewGroup.LayoutParams(size - margin, size)) // width and height

layoutParams.bottomMargin = 8 // horizontal spacing if needed

view.layoutParams = layoutParams

return *your_view_holder_with_view* // usual return
...