How to get the center item after RecyclerView snapped it to center?

YUSMLE picture YUSMLE · Apr 9, 2017 · Viewed 8.3k times · Source

I'm implementing a horizontal RecyclerView that snap items to center after scrolling, like Google play App horizontal lists. This is a review.

My code is below:

MainMenuAdapter mainMenuAdapter = new MainMenuAdapter(this, mDataset);

final LinearLayoutManager layoutManagaer = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

RecyclerView mainMenu = (RecyclerView) findViewById(R.id.main_menu);
mainMenu.setLayoutManager(layoutManagaer);
mainMenu.setAdapter(mainMenuAdapter);

final SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(mainMenu);     

How I can get the center item (position) after RecyclerView snapped it to center? Isn't there any listener implementation for this? Also, when an item view be touched, I want to snap it to center. How can I do this?

Answer

Blackbelt picture Blackbelt · Apr 9, 2017

if you need the View, you can call

 View view =  snapHelper.findSnapView(layoutManagaer);

once you have the View, you should be able to get the position on the dataset for that View. For instance using

   mainMenu.getChildAdapterPosition(view)