Start my RecyclerView Horizontal Carousel from the center item

前端 未结 1 414
旧时难觅i
旧时难觅i 2021-01-12 04:00

I\'m creating a carousel Horizontal RecyclerView with Zoom on focused item that is starting from the first item of the RecyclerView.

Code for custom CenterZ

1条回答
  •  失恋的感觉
    2021-01-12 04:32

    The solution is to change the timing of when LinearSnapHelper is attached to the RecyclerView. The following is a reworked onSetRecyclerView() that will snap the central item of the RecyclerView to the center of the screen. Notice that the LinearSnapHelper is not attached until the RecyclerView is laid out and scrolled appropriately. You do not need to do any scrolling in 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);
            }
        });
    }
    

    This is how the initial screen of my test app is displayed. There are 201 "stores."

    0 讨论(0)
提交回复
热议问题