Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center the Clicked position in the Recyclerview

I want to center the clicked position in the Recyclerview. I am able to scroll the Recyclerview to certain position but i want to middle that position in the screen. I used this method to scroll to that position.

videoRecyclerview.scrollToPosition(position);
like image 450
Shikha Ratra Avatar asked May 17 '16 07:05

Shikha Ratra


People also ask

How do I center items in a RecyclerView?

Take LinearLayout in your RecyclerView 's item row layout then give android:layout_gravity="center" to LinearLayout .

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.

Does RecyclerView have scroll?

To help you build apps with lists, Android provides the RecyclerView . RecyclerView is designed to be very efficient, even with large lists, by reusing, or recycling, the views that have scrolled off the screen.


2 Answers

If you are using a RecyclerView and LinearLayoutManager this will work:

private void scrollToCenter(View v) {
    int itemToScroll = mRecyclerView.getChildPosition(v);
    int centerOfScreen = mRecyclerView.getWidth() / 2 - v.getWidth() / 2;
    mLayoutManager.scrollToPositionWithOffset(itemToScroll, centerOfScreen);
}
like image 75
Ispam Avatar answered Oct 17 '22 07:10

Ispam


if you use linearlayoutManager, you can use this code,

linearLayoutManager.scrollToPositionWithOffset(2, 20);

(linearLayoutManager.void scrollToPositionWithOffset (int position, 
            int offset))

Setting the offset to 0 should align with the top

like image 44
Burak iren Avatar answered Oct 17 '22 06:10

Burak iren