Запустите мой RecyclerView Горизонтальная карусель из центрального пункта - PullRequest
0 голосов
/ 13 сентября 2018

Я создаю карусель Horizontal RecyclerView с Zoom на сфокусированном элементе, который начинается с первого элемента RecyclerView.

Код для пользовательского CenterZoomLayoutManager:

public class CenterZoomLayoutManager extends LinearLayoutManager {
private final float mShrinkAmount = 0.15f;
private final float mShrinkDistance = 0.9f;

public CenterZoomLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
}

@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
    int orientation = getOrientation();
    if (orientation == HORIZONTAL) {

        int scrolled = super.scrollHorizontallyBy(dx, recycler, state);
        float midpoint = getWidth() / 2.f;
        float d0 = 0.f;
        float d1 = mShrinkDistance * midpoint;
        float s0 = 1.f;
        float s1 = 1.f - mShrinkAmount;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            float childMidpoint =
                    (getDecoratedRight(child) + getDecoratedLeft(child)) / 2.f;
            float d = Math.min(d1, Math.abs(midpoint - childMidpoint));
            float scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0);
            child.setScaleX(scale);
            child.setScaleY(scale);
        }
        return scrolled;
    } else return 0;
}

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    super.onLayoutChildren(recycler, state);
    scrollHorizontallyBy(0, recycler, state);
}
}

А в моем Fragment у меня есть следующее:

private void onSetRecyclerView() {

    recyclerView = fragmentView.findViewById(R.id.recyclerView);

    if (recyclerView != null) {
        RecyclerView.LayoutManager layoutManager = new CenterZoomLayoutManager(context, LinearLayoutManager.HORIZONTAL,
                false);

        recyclerView.scrollToPosition(storeList.size() / 2);

        final SnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }
}

Я хочуЗапустите мой RecyclerView из центрального элемента , а не из начальной позиции.

Culprit:
в моем CenterZoomLayoutManager, я устанавливаю начало смещения пикселей от 0 пикселей до scrollHorizontallyBy(0, recycler, state).

Проблема:
Я не могу найти способ передать смещенные пиксели, созданные с помощью recyclerView.scrollToPosition(storeList.size() / 2), в CenterZoomLayoutManager.Я пытался найти другой встроенный метод, чтобы получить X-смещение, но пока не повезло.

1 Ответ

0 голосов
/ 16 сентября 2018

Решение состоит в том, чтобы изменить время, когда LinearSnapHelper присоединен к RecyclerView.Ниже приведен переработанный код onSetRecyclerView(), который привязывает центральный элемент RecyclerView к центру экрана.Обратите внимание, что LinearSnapHelper не прикреплен, пока RecyclerView не выложен и не прокручен надлежащим образом.Вам не нужно выполнять какую-либо прокрутку в onLayoutChildren().

private void onSetRecyclerView() {
    recyclerView = findViewById(R.id.recyclerView);
    CenterZoomLayoutManager layoutManager =
        new CenterZoomLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    // Scroll to the position we want to snap to
    layoutManager.scrollToPosition(storeList.size() / 2);
    // Wait until the RecyclerView is laid out.
    recyclerView.post(new Runnable() {
        @Override
        public void run() {
            // Shift the view to snap  near the center of the screen.
            // This does not have to be precise.
            int dx = (recyclerView.getWidth() - recyclerView.getChildAt(0).getWidth()) / 2;
            recyclerView.scrollBy(-dx, 0);
            // Assign the LinearSnapHelper that will initially snap the near-center view.
            LinearSnapHelper snapHelper = new LinearSnapHelper();
            snapHelper.attachToRecyclerView(recyclerView);
        }
    });
}

. Так отображается начальный экран моего тестового приложения.Есть 201 "магазинов".

enter image description here

...