TrinityTuts

Scrollbar load in recyclerview android

Scrollbar load in recyclerview android

Last updated on March 13th, 2020 at 11:41 am

In my last post i explain how to pass multiple views in RecyclerView. Now in this post i am going to explain how to load data on Scrollbar load in recyclerview. RecyclerView is used in place of Listview in most of application because we can easily convert it into grid view and list with one or two lines. Now we see most of app load data when there scrollbar reaches to end eg. facebook, e-commerce application etc. With help of this tutorial you can learn how easily you can implement this feature on your application.

Scrollbar load in RecyclerView

Step 1. Create new android project in android studio.

Step 2. Create a view which we pass in our RecyclerView Adapter.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:background="#fff"
        android:elevation="1dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:gravity="center_horizontal|center"
                android:src="@drawable/ic_dress" />

            <TextView
                android:id="@+id/product"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Product Name"
                android:padding="10dp" />

        </LinearLayout>
    </android.support.v7.widget.CardView>
</FrameLayout>

Step 3. Now in your activity_main.xml file add RecyclerView and progressbar which we show when user scroll come to end.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.scrolloadrecycleview.MainActivity">

    <ProgressBar
        android:id="@+id/marker_progress"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_below="@+id/recyclerview"
        android:layout_gravity="bottom|center"
        android:indeterminate="true"
        android:visibility="visible" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="50dp"></android.support.v7.widget.RecyclerView>

</FrameLayout>

Note that you need to add RecyclerView dependency in your build.gradle file

compile 'com.android.support:recyclerview-v7:23.4.0'

to use RecyclerView.

Step 4. We need to create Getter Setter to hold data create new class and paste

package com.scrolloadrecycleview;

public class GetterSetter {


    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    String product, image;
}

Step 5. Now we can create Adapter through which we can inflate our view

package com.scrolloadrecycleview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;


public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CustomViewHolder> {
    private List<GetterSetter> feedItemList;
    private Context mContext;

    public ProductAdapter(Context context, ArrayList<GetterSetter> feedItemList) {
        this.feedItemList = feedItemList;
        this.mContext = context;

    }

    @Override
    public ProductAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }


    @Override
    public void onBindViewHolder(CustomViewHolder holder, int position) {
        GetterSetter dc_list = feedItemList.get(position);
        Picasso.with(mContext).load(URLs.imageBAse + "w400-h400/" + dc_list.getImage()).placeholder(R.drawable.ic_dress).into(holder.imageView);
        holder.name.setText(dc_list.getProduct());

    }

    @Override
    public int getItemCount() {
        return (null != feedItemList ? feedItemList.size() : 0);
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        ImageView imageView;

        public CustomViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.image);
            name = (TextView) itemView.findViewById(R.id.product);
        }
    }
}

Step 6. Now open or main activity file where we can request server to load data and also implement scroll load in it. as shown below.

package com.scrolloadrecycleview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements GetResponse {
    int pastVisibleItems, visibleItemCount, totalItemCount;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayoutManager;
    private ArrayList<GetterSetter> arrayList;
    private ProgressBar marker_progress;
    private ProductAdapter adapter;
    private CheckInternet checkInternet;
    private int i;
    private boolean loading;
    private AsyncReuse requestServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        gridLayoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(gridLayoutManager);
        arrayList = new ArrayList<>();
        marker_progress = (ProgressBar) findViewById(R.id.marker_progress);
        adapter = new ProductAdapter(this, arrayList);
        recyclerView.setAdapter(adapter);
        checkInternet = new CheckInternet();
        Context context = this;
        i = 1;
        checkInternet.isNetworkAvailable(context, this);
        if (checkInternet.isConnected) {
            loadData();
            JSONObject jObject = new JSONObject();
            try {
                jObject.put("album_id", "132");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            requestServer.getObjectQ(jObject);
            requestServer.execute();
        }
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Toast.makeText(MainActivity.this, "Item Clicked", Toast.LENGTH_SHORT).show();
                    }
                })
        );
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 0) //check for scroll down
                {
                    visibleItemCount = gridLayoutManager.getChildCount();
                    totalItemCount = gridLayoutManager.getItemCount();
                    pastVisibleItems = gridLayoutManager.findFirstVisibleItemPosition();

                    if (loading) {
                        if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                            loading = false;
                            marker_progress.setVisibility(View.VISIBLE);
                            if (checkInternet.isConnected) {
                                scrollLoad();
                                JSONObject jObject = new JSONObject();
                                try {
                                    i = 2;
                                    jObject.put("page", i);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                requestServer.getObjectQ(jObject);
                                requestServer.execute();
                            }
                        }
                    }
                }
            }
        });
    }

    private void loadData() {
        requestServer = new AsyncReuse(URLs.catalogProducts, true, this);
        requestServer.getResponse = this;
    }

    private void scrollLoad() {
        requestServer = new AsyncReuse(URLs.catalogProducts, false, this);
        requestServer.getResponse = this;
    }

    @Override
    public void getData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response.toString());
            if (jsonObject.getString("status").equals("1")) {
                JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    GetterSetter getterSetter = new GetterSetter();
                    getterSetter.setProduct(object1.getString("product"));
                    getterSetter.setImage(object1.getString("Image"));
                    arrayList.add(getterSetter);
                }
                adapter.notifyDataSetChanged();
                loading = true;
                marker_progress.setVisibility(View.GONE);
            } else {
                loading = false;
                marker_progress.setVisibility(View.GONE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

You are familiare with most of code here in above code i can add some internet check load data from server etc., In above code mode important and new thing is

addOnScrollListener

With help addOnScrollListener we can get scroll position like we do in ListView as explain in my post: Android ListView with Scrolload .

 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 0) //check for scroll down
                {
                    visibleItemCount = gridLayoutManager.getChildCount();
                    totalItemCount = gridLayoutManager.getItemCount();
                    pastVisibleItems = gridLayoutManager.findFirstVisibleItemPosition();

                    if (loading) {
                        if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                            loading = false;
                            marker_progress.setVisibility(View.VISIBLE);
                            if (checkInternet.isConnected) {
                                scrollLoad();
                                JSONObject jObject = new JSONObject();
                                try {
                                    i = 2;
                                    jObject.put("page", i);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                requestServer.getObjectQ(jObject);
                                requestServer.execute();
                            }
                        }
                    }
                }
            }
        });

You can download complete code from above download link.