Skip to content Skip to sidebar Skip to footer

How To Getitemat(position) When Using Viewpager2 With Recyclerviewadapter

I implemented a pretty awesome viewpager2 by setting it to a recyclerView adapter, but I need more than just scrolling it. What I want: I need to get the views inside the layout wh

Solution 1:

If there is a need to extract a view of a single item from a RecyclerView you can use a layout manager of your RecyclerView. Note, that you cannot extract views of items that are not visible on the screen.

Kotlin

val linearLayoutManager = recyclerView.layoutManager as LinearLayoutManager
val position = linearLayoutManager.findFirstVisibleItemPosition()
val view: View? = linearLayoutManager.getChildAt(position)

Java

LinearLayoutManagerlinearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
intposition= linearLayoutManager.findFirstVisibleItemPosition();
@NullableViewview= linearLayoutManager.getChildAt(position);

If you need to do this while scrolling just set RecyclerView.OnScrollListener:

Kotlin

recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() {
    overridefunonScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        // Extract position and view here
    }
})

Java

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        // Extract position and view here
    }
})

You can get all visible items' views if you iterate from the first to the last visible position as there is also findLastVisibleItemPosition().

Post a Comment for "How To Getitemat(position) When Using Viewpager2 With Recyclerviewadapter"