Adding a RecyclerView with grid layout in android

This post describes a simple RecyclerView added as a Fragment in MainActivity.

  1. Create main.xml. In main.xml add a ToolBar in AppBarLayout, and then add a LinearLayout containing a FrameLayout.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent">
	<com.google.android.material.appbar.AppBarLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:theme="@style/AppTheme.AppBarOverlay">
		<androidx.appcompat.widget.Toolbar
			android:id="@+id/_toolbar"
			android:layout_width="match_parent"
			android:layout_height="?attr/actionBarSize"
			android:background="?attr/colorPrimary"
			app:popupTheme="@style/AppTheme.PopupOverlay"/>
	</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
	android:orientation="vertical"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	app:layout_behavior="@string/appbar_scrolling_view_behavior"
	android:id="@+id/sample_main_layout">

	<FrameLayout
		android:id="@+id/sample_content_fragment"
		android:layout_width="match_parent"
		android:layout_height="wrap_content" />

</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

2. In MainActivity.java display ToolBar, enable back button on toolbar, and create fragment transaction to display fragment.

package com.sanju.doc.calculator;

import android.os.*;
import android.view.*;
import android.util.*;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);
		setContentView(R.layout.main);

		Toolbar _toolbar = (Toolbar) findViewById(R.id._toolbar);
		setSupportActionBar(_toolbar);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);
		_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View _v) {
				onBackPressed();
			}
		});

		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		RecyclerViewFragment fragment = new RecyclerViewFragment();
		transaction.replace(R.id.sample_content_fragment, fragment);
		transaction.commit();

	}

}

3. Create recycle_view_frag.xml containing a RecyclerView. This will be the main view of the Fragment layout.

<?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">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

4. Create text_row_item.xml containing a TextView. This will be view of each item in RecyclerView.

<?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="wrap_content"
    android:gravity="center_vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="134dp"
        android:text="Title"
        android:background="#dfffed"
        android:gravity="center_horizontal|center_vertical"
        android:padding="6dp"
        android:textColor="#224422"
        android:textStyle="bold"
        android:textSize="14sp" />
</FrameLayout>

5. Create RecyclerViewFragment.java and put following codes in it.

package com.sanju.doc.calculator;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerViewFragment extends Fragment {

    private static final String TAG = "RecyclerViewFragment";

    protected RecyclerView mRecyclerView;
    protected CustomAdapter mAdapter;
    protected RecyclerView.LayoutManager mLayoutManager;
    protected String[] mDataset;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initDataset();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.recycle_view_frag, container, false);
        rootView.setTag(TAG);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);

        mAdapter = new CustomAdapter(mDataset);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new GridLayoutManager(getActivity(), 2);
        mRecyclerView.setLayoutManager(mLayoutManager);

        return rootView;
    }

    private void initDataset() {
        mDataset = new String[16];
            mDataset[0] = "Age Calculator";
            mDataset[1] = "Anti Rabies Vaccine Schedule";
            mDataset[2] = "Body Mass Index";
            mDataset[3] = "Creatinine Clearance";
            mDataset[4] = "Fluid Resuscitation in Burns";
            mDataset[5] = "Gestational Age from LMP";
            mDataset[6] = "Gestational Age from scan";
            mDataset[7] = "Glomerular Filtration Rate";
            mDataset[8] = "Temperature conversion";
            mDataset[9] = "Arm Fat Index";
            mDataset[10] = "Basal Metabolic Rate";
            mDataset[11] = "Body Adiposity Index";
            mDataset[12] = "Body Surface Area";
            mDataset[13] = "Fractional Excretion of Sodium";
            mDataset[14] = "Mean Arterial Pressure";
            mDataset[15] = "Plasma Osmolality";
    }

    public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
        private static final String TAG = "CustomAdapter";

        private String[] mDataSet;

        public class ViewHolder extends RecyclerView.ViewHolder {
            private final TextView textView;

            public ViewHolder(View v) {
                super(v);
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "Item " + getAdapterPosition() + " clicked.", Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
                    }
                });

                textView = (TextView) v.findViewById(R.id.textView);
            }

            public TextView getTextView() {
                return textView;
            }
        }

        public CustomAdapter(String[] dataSet) {
            mDataSet = dataSet;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            // Create a new view.
            View v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.text_row_item, viewGroup, false);

            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            Log.d(TAG, "Element " + position + " set.");

            viewHolder.getTextView().setText(mDataSet[position]);
        }

        @Override
        public int getItemCount() {
            return mDataSet.length;
        }
    }

}

Now run the project and see the results. The View will look as shown in image below. Don’t forget to change the package name at top in java files to your package name.

grid_layout
Grid RecyclerView