5

How can I get a current item in RecycerView? In my use-case RV item takes all screen space, so there is only one item at a time. I've tried to google before, but nothing helpful was found.

The whole use case:

  1. UI. The bottom navigation has a button that should call a certain method (let's say a foo() method) in fragment

  2. this foo() method should get a visible item from the adapter and call a specific method in a presenter.

James Z
  • 12,209
  • 10
  • 24
  • 44
P. Savrov
  • 1,064
  • 4
  • 17
  • 29

3 Answers3

4

use this in your code

    LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

and get your visible item using below code

mLayoutManager.findFirstVisibleItemPosition();
Vinayak B
  • 4,430
  • 4
  • 28
  • 58
  • yeah, I can get a position, but how I can get an item? Even more, based on this answer (https://stackoverflow.com/a/25053500/1752729), it is not the best approach – P. Savrov Aug 21 '17 at 13:29
1

You could also use an OnItemClickListener on your RecyclerView's ListAdapter to determine the current item. In that case the item needs to be clicked though.

eheller
  • 117
  • 1
  • 1
  • 13
0

My solution

val position = (recyclerView?.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
val product = adapter?.getItemByPosition(position)
FirebaseCrash.logcat(Log.DEBUG, TAG, "onNavClickEvent = $product")
product?.let { productListViewModel?.order(it.id) }

The result is:

onNavClickEvent = Product(id=1, title='Cap', description='some descr.', price=10, photo='http://lorempixel.com/200/200/sports/1/')
P. Savrov
  • 1,064
  • 4
  • 17
  • 29