Android GridView with Recyclerview

A Recyclerview is an advanced and flexible version of  a listview. RecyclerView ViewGroup is a container for larger data set of views that can be recycled and scrolled very efficiently. For using RecyclerView you need to specify an  adapter and layout manager also. A layout manager positions items views inside a recyclerview and determines when to reuse that item when it no longer visible to user.

There are some built-in Layout mangers available for recyclerview. Here we are using GridLayoutManager for implementing a recyclerview which will display items as Grids. In this tutorial we will learn how to implement a recyclerview in android

Steps

  1. Create new project in android studio
  2. Add recyclerview widget to your layout file
  3. Implement layout for recyclerview item.
  4. Create recyclerview adapter
  5. Set adapter to recyclerview with data.

Create New project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Add the recyclerview widget to your layout file

After creating new project in android studio ,an activity with layout and java file will be automatically created if you haven’t change any defaults. For implementing the recyclerview in your activity you need to add the following code to your layout file.

<android.support.v7.widget.RecyclerView
        android:id="@+id/rv_cards"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"/>

Implement layout for recyclerview item

Now we need to have a layout item file . This file will have the design for individual item in the recyclerview .So you need to create a file under res/layout/layout_languages_item.xml. Here i am showing only cards with one textview. you can use widgets like imageview,Button etc in this file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="150dp"
        android:layout_height="150dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/card_background">

            <TextView
                android:id="@+id/tv_languages"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:textSize="24sp"
                android:textColor="@color/white"/>

        </RelativeLayout>

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

</LinearLayout>

Create recyclerview adapter

Like listview recyclerview should also have an adapter class which will inflate your item layout (the layout which is created in above layout)  and set data to views inside the layout. If there is only one text data in recyclerview you can use default array adapter which just pass string .But if you need multiple items to set in recyclerview you need to have a model class with constructor and getter’s and settor’s. For having that create a class under java/your package name/LanguageModel.java

public class LanguageModel {
    String id,language;

    public LanguageModel(String id, String language) {
        this.id = id;
        this.language = language;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}

Now we can create the adapter for the recyclerview .For creating the adapter create a file in the same location with the following name and add the following code into it. The constructor here will be having the array list of  model class which we created above

LanguageListAdapter.java
public class LanguageListAdapter extends RecyclerView.Adapter<LanguageListAdapter.SingleItemRowHolder> {

    private ArrayList<LanguageModel> itemsList;
    private Activity mContext;
    int layout;

    public LanguageListAdapter(Activity context, ArrayList<LanguageModel> itemsList, int layout) {
        this.itemsList = itemsList;
        this.mContext = context;
        this.layout = layout;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(layout, null);
        SingleItemRowHolder mh = new SingleItemRowHolder(v);
        return mh;
    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        LanguageModel item = itemsList.get(i);

        holder.tv_languages.setTag(i);
        holder.tv_languages.setText(item.getLanguage());

    }

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

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tv_languages;


        public SingleItemRowHolder(View view) {
            super(view);

            this.tv_languages = (TextView) view.findViewById(R.id.tv_languages);


            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    int position = Integer.parseInt(tv_languages.getTag().toString());

                   Toast.makeText(v.getContext(), tv_languages.getText(), Toast.LENGTH_SHORT).show();

                }
            });


        }

    }

}

We need one more class DividerItemDecoration.java .What this class will do is that it will help to give divider space  between each items in a recyclerview. Here is the code for DividerItemDecoration.java.

DividerItemDecoration.java
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

    public DividerItemDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;


        //for vertical scrolling
      outRect.bottom = space;
      outRect.top = space;} }

Set adapter to recyclerview with data

This is the final step in which you need to replace the code of your activity with the following code. The code is performing following operations.

  1. Initialization of recyclerview
  2. Referring recyclerview from layout.
  3. Setting layout manager for recyclerview
  4. Initializing recyclerview adapter and setting up data
  5. Setting adapter to recyclerview
public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    RecyclerView rv_cards;
    LanguageListAdapter languageListAdapter;
    ArrayList<LanguageModel> languageModels;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //methode for initialisation
        init();


    }

    private void init() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Languages");

        //initialisation of recycler view
        rv_cards = (RecyclerView) findViewById(R.id.rv_cards);

        //setting layout manager .Here in GridLayoutManager constructor you need to specify the number
        //of coloms in you want in grid .Here it is 2
        
        rv_cards.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
        rv_cards.addItemDecoration(new DividerItemDecoration(10));


        languageModels = new ArrayList<>();

        //adding few datas into array list

            languageModels.add(new LanguageModel("1","Android"));
            languageModels.add(new LanguageModel("2","C++"));
            languageModels.add(new LanguageModel("3","C"));
            languageModels.add(new LanguageModel("4","Python"));
            languageModels.add(new LanguageModel("5","Java Script"));
            languageModels.add(new LanguageModel("6","Java"));
            languageModels.add(new LanguageModel("7","Sql"));
            languageModels.add(new LanguageModel("8","PHP"));
            languageModels.add(new LanguageModel("9","MySql"));
            languageModels.add(new LanguageModel("10","Asp.Net"));

        //initialisation of recycler adapter
        languageListAdapter = new LanguageListAdapter(MainActivity.this, languageModels, R.layout.layout_languages_item);

        //setting adapter to recycler
        rv_cards.setAdapter(languageListAdapter);
    }

}

Output

recycler-gridview

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *