Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set item to center of Recycler view when selected

I am using a RecyclerView to display items horizontally. I want to set the selected item to center of the view like this

enter image description here.

This is how I am doing it:

LinearLayoutManager layoutManager
                = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(layoutManager);
like image 881
ravi Avatar asked Jan 14 '16 11:01

ravi


People also ask

How do you tell the RecyclerView to start at a specific item position?

If onLayoutChildren is called by RecyclerView, it checks if adapters itemCount is already > 0. If true, it calls scrollToPositionWithOffset() . So I can tell immediately what position should be visible, but it will not be told to LayoutManager before position exists in Adapter. Show activity on this post.

How do I center items in a recyclerview when scrolling?

An OnScrollListener can be added to a RecyclerView to receive messages when a scrolling event has occurred on that RecyclerView. When the recycler views vertically scrolls, then the selected item to be centered or on the Top First item, and then the item is automatically centered or to be the first when the item to be selected is set.

How to get clicked item and its position in recyclerview?

This example demonstrate about how to get clicked item and its position in RecyclerView. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.

How to center a row of images in a recyclerview?

Take LinearLayoutin your RecyclerView's item row layout then give android:layout_gravity="center"to LinearLayout. For each row of images you have to take different LinearLayout. Here is example code:

Is it possible to center items in Recycler view with grid layout?

Dec 5 '15 at 0:11 For my project using recycler view with grid layout, where items are centered using gravity attribute works fine. – MikeL Nov 29 '16 at 1:04


3 Answers

To obtain middle item on your screen from RecyclerView you can attach OnScrollListener to RecyclerView and inside listener you should get position of current items then you should check if area of given item is on middle of screen.

Code sample in Kotlin:

// Attach OnScrollListener to your RecyclerView
addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        recyclerView.post {
            selectMiddleItem()
        }
    }
})
// implementation of method that is called from OnScrollListener
private fun selectMiddleItem() {
    val firstVisibleIndex = layoutManager.findFirstVisibleItemPosition()
    val lastVisibleIndex = layoutManager.findLastVisibleItemPosition()
    val visibleIndexes = listOf(firstVisibleIndex..lastVisibleIndex).flatten()

    for (i in visibleIndexes) {
        val vh = findViewHolderForLayoutPosition(i)
        if (vh?.itemView == null) {
            continue
        }
        val location = IntArray(2)
        vh.itemView.getLocationOnScreen(location)
        val x = location[0]
        val halfWidth = vh.itemView.width * .5
        val rightSide = x + halfWidth
        val leftSide = x - halfWidth
        val isInMiddle = screenWidth * .5 in leftSide..rightSide
        if (isInMiddle) {
            // "i" is your middle index and implement selecting it as you want 
            // optionsAdapter.selectItemAtIndex(i)
            return
        }
    }
}

And as result you should get something like this:

enter image description here

like image 51
Paweł Kanarek Avatar answered Sep 18 '22 15:09

Paweł Kanarek


This is for snapping the item in the center when scrolling, or when clicking on an ite.

You need to have a SnapHelper added to the RecyclerView. Here is how:

final RecyclerView recyclerViewObject = view.findViewById(R.id.recyclerViewObjectId);

final LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerViewObject);

recyclerViewObject.setOnFlingListener(snapHelper);

then you just call this code

recyclerViewObject.addOnItemTouchListener(
            new RecyclerItemClickListener(getContext(), recyclerViewObject ,new RecyclerItemClickListener.OnItemClickListener() {
                @Override public void onItemClick(View view, int position) {
                    recyclerViewObject.smoothScrollToPosition(position);
                }

                @Override public void onLongItemClick(View view, int position) {
                }
            })
    );
like image 28
Cosmin Badulescu Avatar answered Sep 19 '22 15:09

Cosmin Badulescu


You can achieve the same output with minimal lines of code. Where, view is view of selected adapter item and StaticData.SCREEN_WIDTH is device width.

    View view = rvCategory.getChildAt(pos);
    if (view == null)
        return;
    int scrollX = (view.getLeft() - (StaticData.SCREEN_WIDTH / 2)) + (view.getWidth() / 2);
    rvCategory.smoothScrollBy(scrollX, 0);
like image 22
DKHirani Avatar answered Sep 17 '22 15:09

DKHirani