Android Horizontal RecyclerView CardView And Images Example

runtime permissions with dexter, android runtime permissions, horizontal listview android, android horizontal recyclerview

Android Horizontal RecyclerView CardView And Images Example Tutorial is written here.

Generally, we create vertical recyclerview to show the data in tabular manner.

In this tutorial, we will implement a recyclerview with the horizontal variant instead of vertical.

By default, recyclerview is vertical but android provides a built in method to make recyclerview horizontal.

While we do not have any such method in ListView. So it is easier to make horizontal recyclerview than horizontal listview.

Of course we get same functionality if we make horizontal listview but it is little complex task.

Web Host Recommendation

If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.

Click this link to see affordable plans.

(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)

Look of horizontal Recyclerview

If you want to create a horizontal listview then

read how to implement horizontal listview in android.

Follow all the below steps to make horizontal recyclerview.

Step 1. Making Dependencies

To implement recyclerview and cardview, we need to add dependencies separately.

Write the following lines in build.gradle(Module: app)

implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'

These lines will fetch required classes to use recyclerview and cardview in your android app.

Step 2. Special Layout File

In recyclerview, we need to create additional layout xml file.

This file will create a view for every single row item. Adapter class will inflate this file while generating the recyclerview row items.

Make a new file res->layout structure. Give it a name as recycler_item.xml

Copy the following source code in recycler_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="5dp"
        android:layout_margin="5dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:orientation="vertical">

            <ImageView
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:src="@drawable/apple"
                android:scaleType="fitXY"
                android:id="@+id/iv" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/tv"
                android:gravity="center"
                android:text="Image"
                android:textColor="#000"
                android:textSize="18sp" />

        </LinearLayout>

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

</LinearLayout>

As we want to make a cardview, here I have set it in the above file.

Cardview is the parent of all the other views.

Then inside cardview, I have taken one Linearlayout with vertical orientation.

Inside this linearlayout, one imageview and one textview is present. Imageview will be above the textview.

Downloading Images

We will set fruit images in our horizontal recyclerview.

You can download the required fruit images by clicking the below link.

Download fruit Images

After downloading the images, copy them into the res->drawable directory.

Step 3. Fruit Model

Now let us create a model class. This class is useful to maintain proper data structure.

Create a new class named “FruitModel.java” and add the following code in it.

public class FruitModel {

    private String name;
    private int image_drawable;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getImage_drawable() {
        return image_drawable;
    }

    public void setImage_drawable(int image_drawable) {
        this.image_drawable = image_drawable;
    }
}

This class includes the getter ans setter methods for all the UI widgets which are present in the every row of the recyclerview.

In this example, we have one imageview and textview each, so this model have methods for image and text as you can show in the above code.

Step 4. Fruit Adapter

Adapter class will use the data and will create a recyclerview.

Prepare a new class named “FruitAdapter.java”

Write down the below coding lines in “FruitAdapter.java”

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 java.util.ArrayList;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<FruitModel> imageModelArrayList;

    public FruitAdapter(Context ctx, ArrayList<FruitModel> imageModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.imageModelArrayList = imageModelArrayList;
    }

    @Override
    public FruitAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.recycler_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(FruitAdapter.MyViewHolder holder, int position) {

        holder.iv.setImageResource(imageModelArrayList.get(position).getImage_drawable());
        holder.time.setText(imageModelArrayList.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return imageModelArrayList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView time;
        ImageView iv;

        public MyViewHolder(View itemView) {
            super(itemView);

            time = (TextView) itemView.findViewById(R.id.tv);
            iv = (ImageView) itemView.findViewById(R.id.iv);
        }

    }
}

Looking Heavily At Adapter

Let us understand the below code

 public FruitAdapter(Context ctx, ArrayList<FruitModel> imageModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.imageModelArrayList = imageModelArrayList;
    }

Above is the constructor of FruitAdapter class. It has two parameters.

First parameter will get context and second will get arraylist (imageModelArraList) of the objects of the FruitModel class.

This arraylist imageModelArraList will provide appropriate data to the adapter class.

 onBindViewHolder() method

Below is the code for onBindViewHolder() method.

 @Override
    public void onBindViewHolder(FruitAdapter.MyViewHolder holder, int position) {

        holder.iv.setImageResource(imageModelArrayList.get(position).getImage_drawable());
        holder.time.setText(imageModelArrayList.get(position).getName());
 }

This method will set text in textview and image in the imageview.

It will use that arraylist (imageModelArraList ) to fetch the data.

Compiler will call this method for number of time which is equal to the number of rows in the recyclerview.

Step 5. Last Modifications

Last but not least, make changes in the activity_main.xml and MainActivity.java file.

Copy the following code snippet in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="15dp"/>

</android.support.constraint.ConstraintLayout>

In the main layout file, I have write only recyclerview code.

Code snippet for MainActivity.java will be as below

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ArrayList<FruitModel> imageModelArrayList;
    private FruitAdapter adapter;

    private int[] myImageList = new int[]{R.drawable.apple, R.drawable.mango,R.drawable.straw, R.drawable.pineapple,R.drawable.orange,R.drawable.blue,R.drawable.water};
    private String[] myImageNameList = new String[]{"Apple","Mango" ,"Strawberry","Pineapple","Orange","Blueberry","Watermelon"};

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler);

        imageModelArrayList = eatFruits();
        adapter = new FruitAdapter(this, imageModelArrayList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));

    }

    private ArrayList<FruitModel> eatFruits(){

        ArrayList<FruitModel> list = new ArrayList<>();

        for(int i = 0; i < 7; i++){
            FruitModel fruitModel = new FruitModel();
            fruitModel.setName(myImageNameList[i]);
            fruitModel.setImage_drawable(myImageList[i]);
            list.add(fruitModel);
        }

        return list;
    }

}

How does MainActivity.java works ?

Consider the following source code

 private RecyclerView recyclerView;
    private ArrayList<FruitModel> imageModelArrayList;
    private FruitAdapter adapter;

    private int[] myImageList = new int[]{R.drawable.apple, R.drawable.mango,R.drawable.straw, R.drawable.pineapple,R.drawable.orange,R.drawable.blue,R.drawable.water};
    private String[] myImageNameList = new String[]{"Apple","Mango" ,"Strawberry","Pineapple","Orange","Blueberry","Watermelon"};

Line one is creating an object of the RecyclerView class.

Second line is making an arraylist with the objects of the FruitModel class.

Third will create an object of FruitAdapter class.

Fourth line will create one integer array named myImageList. This myImageList contains as integer reference of the fruit images present in the drawable folder.

Fifth line makes a string array myImageNameList.

myImageNameList holds the names of the fruits.

Attend the following code

 imageModelArrayList = eatFruits();

Above line is populating an arraylist using the eatFruits method.

Below is the code for eatFruits() methods.

 private ArrayList<FruitModel> eatFruits(){

        ArrayList<FruitModel> list = new ArrayList<>();

        for(int i = 0; i < 7; i++){
            FruitModel fruitModel = new FruitModel();
            fruitModel.setName(myImageNameList[i]);
            fruitModel.setImage_drawable(myImageList[i]);
            list.add(fruitModel);
        }

        return list;
    }

This method will rotate a for loop with seven iterations.

During every iterations, compiler will create an object of the FruitModel class.

Then it will set the image integer reference and image name to that object.

After that compiler will add this object in to the arraylist and this process continues for seven times.

Read the following coding lines

 adapter = new FruitAdapter(this, imageModelArrayList);
 recyclerView.setAdapter(adapter);
 recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));

Compiler will create an object of FruitAdapter class with required parameters during first line.

By reading the second line, system will set the adapter with the recyclerview.

Now third line is the most important for us.

It will set the layout to the recyclerview. We are telling compiler to make our recyclerview horizontal in this line. 

So, now if you run your project, you should get the output like the video you watched at the starting of the tutorial.

Web Host Recommendation

If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.

Click this link to see affordable plans.

(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)

 Download Source Code For Android Horizontal RecyclerView

[sociallocker]Download Source Code For Recyclerview_Horizontal[/sociallocker]