Как сделать карточки в RecyclerView квадратными в разном DPI - PullRequest
0 голосов
/ 07 июля 2019

Я создаю макет, очень похожий на Instagram

Я хочу показать пользователям мультимедиа в повторном обзоре с 3 столбцами

Это моя карта:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_gravity="center"
    android:layout_margin="1dp">

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/mediaThumbnail"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/link_blue"
        android:scaleType="centerCrop" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/likes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/mediaThumbnail"
        android:layout_alignBottom="@id/mediaThumbnail"
        android:layout_margin="2dp"
        android:drawableLeft="@drawable/ic_like"
        android:text="10001"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="12sp" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/comments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/mediaThumbnail"
        android:layout_alignBottom="@id/mediaThumbnail"
        android:layout_margin="2dp"
        android:drawableLeft="@drawable/ic_comments"
        android:text="10001"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="12sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="17dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="1dp"
        android:background="#33000000" />

и вот как я запускаю обзор рециркулятора:

  RecyclerView recyclerView = findViewById(R.id.gridView);
        recyclerView.setAdapter(new MediaAdapter(new ArrayList<>()));
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

моя точка зрения: разные устройства будут иметь разную ширину экрана, поэтому я не могу принудительно установить любое значение на карте android:layout_width="match_parent" я позволю раскладщику делатьэто задание

но тогда я не знаю, какое значение у него закончилось, поэтому любое значение, которое я пытаюсь угадать для android:layout_height="100dp", не будет квадратным.

это окончательный результат: enter image description here

как отрегулировать высоту, чтобы получить значение ширины во время выполнения?

Ответы [ 2 ]

0 голосов
/ 07 июля 2019

Вы можете сделать это следующим образом:

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = view.getWidth();
        view.setLayoutParams(params);
        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

Нет (за исключением того, что View с ConstraintLayout) реального способа достичь этого с помощью xml.Код, который я написал, выполняет следующее: когда вызывается onGlobalLayout, ваш размер Views был установлен.Теперь при доступе к LayoutParams он будет иметь правильные значения.Тогда я просто говорю, что высота должна быть равна ширине.Последняя строка удаляет слушателя, поскольку его подключение будет стоить производительности.

0 голосов
/ 07 июля 2019

Лучший способ достичь этого результата - обернуть ваш макет с помощью ConstraintLayout. Пожалуйста, посмотрите на код ниже.

<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">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_margin="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/mediaThumbnail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/link_blue"
            android:scaleType="centerCrop" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/likes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/mediaThumbnail"
            android:layout_alignBottom="@id/mediaThumbnail"
            android:layout_margin="2dp"
            android:drawableLeft="@drawable/ic_like"
            android:text="10001"
            android:textAlignment="center"
            android:textColor="#000000"
            android:textSize="12sp" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/comments"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@id/mediaThumbnail"
            android:layout_alignBottom="@id/mediaThumbnail"
            android:layout_margin="2dp"
            android:drawableLeft="@drawable/ic_comments"
            android:text="10001"
            android:textAlignment="center"
            android:textColor="#000000"
            android:textSize="12sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="17dp"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="1dp"
            android:background="#33000000" />
    </RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
...