get visible item count of recycler view; - Android User Interface

Android examples for User Interface:RecyclerView

Description

get visible item count of recycler view;

Demo Code


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class Main{
    /**//  w  w w  .  j  a va  2s.  com
     * get visible item count of recycler view;
     *
     * @param rv
     * @return
     */
    public static int getVisibleItemCount(RecyclerView rv) {
        final int firstVisiblePos = getFirstVisiblePosition(rv);
        final int lastVisiblePos = getLastVisiblePosition(rv);
        return Math.max(0, lastVisiblePos - firstVisiblePos);
    }
    /**
     * get first visible position of recycler view
     *
     * @param rv
     * @return
     */
    public static int getFirstVisiblePosition(RecyclerView rv) {
        if (rv != null) {
            final RecyclerView.LayoutManager layoutManager = rv
                    .getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                return ((LinearLayoutManager) layoutManager)
                        .findFirstVisibleItemPosition();
            }
        }
        return 0;
    }
    /**
     * get last visible position of recycler view
     *
     * @param rv
     * @return
     */
    public static int getLastVisiblePosition(RecyclerView rv) {
        if (rv != null) {
            final RecyclerView.LayoutManager layoutManager = rv
                    .getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                return ((LinearLayoutManager) layoutManager)
                        .findLastVisibleItemPosition();
            }
        }
        return 0;
    }
}

Related Tutorials