Search code examples
androidandroid-recyclerviewsnapping

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


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?


Solution

  • 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)