Как настроить RecyclerView с помощью GridLayoutManager, чтобы он соответствовал ширине экрана устройства? - PullRequest
1 голос
/ 25 мая 2019

У меня есть RecyclerView, который я хочу всегда иметь 3 столбца.По какой-то причине ширина при использовании GridLayoutManager кажется статической шириной, и я не уверен, как заставить ее соответствовать экрану.

В iOS это легко, так как я использую UICollectionViewи auto layout управляет таким образом:

How width should look.

Как получить такой же результат на Android?Вот мой content_symptom_tracker.xml:

<?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="match_parent"
android:background="@color/bzPrimary"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".SymptomTracker"
tools:showIn="@layout/activity_symptom_tracker">

<com.cryptixltd.peterruppert.brainzaps.GridRecyclerView
    android:id="@+id/symptomRecycler"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:foregroundGravity="center"
    android:layoutAnimation="@anim/grid_layout_animation_from_bottom"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

Вот как я настраиваю Recycler в Activity:

  recyclerView = findViewById(R.id.symptomRecycler);
    int numberOfColumns = 3;
    recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
    adapter = new SymptomAdapter(this, common_symptoms);
    recyclerView.setAdapter(adapter);

Но он дает мне такой же результат, одинаковой ширины независимо от устройства:

enter image description here

Я не хочу менять размер значков, просто сделайте так, чтобы интервал ширины совпадал с родительским.

Спасибо!

РЕДАКТИРОВАТЬ: Вот класс GridRecyclerView, это пользовательский класс, чтобы помочь с Grid Animations:

  public class GridRecyclerView extends RecyclerView {

public GridRecyclerView(Context context) { super(context); }


public GridRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); }


public GridRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }

@Override
protected void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params,
                                               int index, int count) {
    final LayoutManager layoutManager = getLayoutManager();
    if (getAdapter() != null && layoutManager instanceof GridLayoutManager){

        GridLayoutAnimationController.AnimationParameters animationParams =
                (GridLayoutAnimationController.AnimationParameters) params.layoutAnimationParameters;

        if (animationParams == null) {
            // If there are no animation parameters, create new once and attach them to
            // the LayoutParams.
            animationParams = new GridLayoutAnimationController.AnimationParameters();
            params.layoutAnimationParameters = animationParams;
        }

        // Next we are updating the parameters

        // Set the number of items in the RecyclerView and the index of this item
        animationParams.count = count;
        animationParams.index = index;

        // Calculate the number of columns and rows in the grid
        final int columns = ((GridLayoutManager) layoutManager).getSpanCount();
        animationParams.columnsCount = columns;
        animationParams.rowsCount = count / columns;

        // Calculate the column/row position in the grid
        final int invertedIndex = count - 1 - index;
        animationParams.column = columns - 1 - (invertedIndex % columns);
        animationParams.row = animationParams.rowsCount - 1 - invertedIndex / columns;

    } else {
        // Proceed as normal if using another type of LayoutManager
        super.attachLayoutAnimationParameters(child, params, index, count);
    }
}

}

1 Ответ

0 голосов
/ 26 мая 2019

попытайтесь установить GridRecyclerView для соответствия ограничениям.в твоем случае просто сделай андроид: layout_width = 0dp.

...