findFirstVisibleItemPositions doesn't work for recycleview android

I tested it with this code and it works fine with me

int positionView = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();

I used the recycle view parameter.


Try this:

int position = layoutManager.findFirstVisibleItemPositions(null)[0];

where layoutManager is what you set in your recyclerview.

For example,

layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mrecyclerView.setLayoutManager(layoutManager );

Use these two methods :

    /**
     * @return Last visible item position for staggeredGridLayoutManager
     */
    private int getLastVisibleItem(int[] lastVisibleItemPositions) {
        int maxSize = 0;
        for (int position : lastVisibleItemPositions) {
            if (position > maxSize) {
                maxSize = position;
            }
        }
        return maxSize;
    }

    /**
     * @return First visible item position for staggeredGridLayoutManager
     */
    private int getFirstVisibleItem(int[] firstVisibleItemPositions) {
        int minSize = 0;
        if (firstVisibleItemPositions.length > 0) {
            minSize = firstVisibleItemPositions[0];
            for (int position : firstVisibleItemPositions) {
                if (position < minSize) {
                    minSize = position;
                }
            }
        }
        return minSize;
    }

and getLastVisibleItem method as below:

                    int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(null);
                    int[] firstVisibleItemPositions = ((StaggeredGridLayoutManager) layoutManager).findFirstVisibleItemPositions(null);
                    // get maximum element within the list
                    lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
                    firstVisibleItem = getFirstVisibleItem(firstVisibleItemPositions);