Android tutorial

Android RecyclerView and its working?

recyclerview

In this android Tutorial we are learn about how to used RecyclerView in android show the a list of item data with Cardview design.

Also You can learn how to used Adapter and how to mange item click in the list. How to change Recyclerview item color in android. we learn to change item color when it clicks. Hey here is the solution to changing the background color of a selected list item in the recycler view list. it’s very easy you can just follow the step for Changing the background color of the selected item in recycler view.

Working With RecyclerView in android

You just follow below steps for full example with new  android studio. So first you can create a android project if you have not and follow below steps. Also check project dependencies below.

dependencies {

    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    implementation 'com.squareup.picasso:picasso:2.5.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

 

Step 1: Add Recyclerview in you XML class.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

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

    </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

 

Step 2: Create a new XML file item_view_card.xml for List item View UI.

this is a list item UI whare i am showing heading, image, discerption, etc more.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/VideoCardViw"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="5dp">

    <LinearLayout
        android:id="@+id/LinverLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/video_card_color"
        android:orientation="horizontal">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_vertical"
            android:padding="10dp"
            android:layout_weight="1">

            <TextView
                android:id="@+id/VideoTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="15dp"
                android:maxLines="1"
                android:textColor="@color/black"
                android:text="video"/>

            <TextView
                android:id="@+id/VideoDisscrption"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="12dp"
                android:maxLines="2"
                android:textColor="@color/black"
                android:text="video"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/VideoTime"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="10dp"
                    android:layout_weight="1"
                    android:textColor="@color/black"
                    android:gravity="center_vertical"
                    android:drawablePadding="10dp"
                    android:text="15 Minutes ago"/>

                <TextView
                    android:id="@+id/VideoReadMore"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="10dp"
                    android:layout_weight="1"
                    android:textColor="@color/black"
                    android:gravity="center_vertical"
                    android:drawablePadding="10dp"
                    android:text="Read More..."/>
            </LinearLayout>
        </LinearLayout>


        <RelativeLayout
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:gravity="center">

            <com.google.android.material.imageview.ShapeableImageView
                android:id="@+id/VideoThemblen"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:padding="2dp"
                app:strokeColor="@color/white"
                app:shapeAppearanceOverlay="@style/circleImageView"
                app:strokeWidth="2dp"
                android:src="@android:drawable/ic_menu_gallery"/>

            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerInParent="true"
                android:src="@android:drawable/ic_media_play"
                app:tint="@color/white" />

        </RelativeLayout>

    </LinearLayout>

</androidx.cardview.widget.CardView>

 

Step 3: Create A Java class Adapter RecyclerViewAdapter.

make a adapter class to add the you model class data to set in adapter. And in RecyclerViewAdapter  you can set the list date to the item Ui. And Liston the item click and other UI function.

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;

    private LayoutInflater inflater;
    int index =0;
    List<VideoDataItem> data = Collections.emptyList();
    private ArrayList<VideoDataItem> arraylist;

    SimpleDateFormat format1=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");



    private int lastPosition = -2;
    public RecyclerViewAdapter(Context context, List<VideoDataItem> data) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.data = data;
        this.arraylist = new ArrayList<VideoDataItem>();
        this.arraylist.addAll(data);
    }

    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.from(parent.getContext()).
                inflate(R.layout.item_video_card, parent, false);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        MyHolder myHolder = (MyHolder) holder;
        VideoDataItem current = data.get(position);
        myHolder.VideoTitle.setText(current.getTitle());
        myHolder.VideoDisscrption.setText(current.getDescription());
        myHolder.VideoTime.setText(current.getVideoDate());

        myHolder.VideoCardViw.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View view) {
                index = myHolder.getAdapterPosition();
                notifyDataSetChanged();
            }
        });
        if(index== position){
            myHolder.LinverLayout.setBackgroundColor(Color.parseColor("#FFEB3B"));
        } else {
            myHolder.LinverLayout.setBackgroundColor(Color.parseColor("#E3E4E6"));
        }


        String userImage = current.getImage();
        if (userImage.isEmpty()||userImage.equals(null)||userImage.equals("")) {

        } else {
            Picasso.with(context)
                    .load(userImage)
                    .placeholder(R.drawable.ic_launcher_background)
                    .fit()
                    .into( myHolder.VideoThemblen);
        }
        setAnimation(myHolder.itemView, position);

    }

    private void setAnimation(View viewToAnimate, int position)
    {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition)
        {
            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        data.clear();
        if (charText.length() == 0) {
            data.addAll(arraylist);
        } else {
            for (VideoDataItem wp : arraylist) {
                if (wp.getTitle().toLowerCase(Locale.getDefault()).contains(charText)) {
                    data.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

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


    class MyHolder extends RecyclerView.ViewHolder {


        CardView VideoCardViw;
        TextView VideoDisscrption;
        TextView VideoTime;
        LinearLayout LinverLayout;
        ImageView VideoThemblen;
        TextView VideoReadMore;
        TextView VideoTitle;


        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            VideoCardViw = itemView.findViewById(R.id.VideoCardViw);
            VideoDisscrption = itemView.findViewById(R.id.VideoDisscrption);
            LinverLayout  = itemView.findViewById(R.id.LinverLayout);
            VideoTime = itemView.findViewById(R.id.VideoTime);
            VideoThemblen = itemView.findViewById(R.id.VideoThemblen);
            VideoReadMore = itemView.findViewById(R.id.VideoReadMore);
            VideoTitle = itemView.findViewById(R.id.VideoTitle);
            VideoReadMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    String url = data.get(position).getUrl();

                }
            });


        }
    }

}

 

Step 3:  Create a Data Model Class.

in your model class you can create a getter and setter for you API date and parser.

package com.lcodeplayon.recyclerview;

public class VideoDataItem {
    private String image;
    private String videoDate;
    private String description;
    private String title;
    private String url;

    public String getImage(){
        return image;
    }

    public String getVideoDate(){
        return videoDate;
    }

    public String getDescription(){
        return description;
    }

    public String getTitle(){
        return title;
    }

    public String getUrl(){
        return url;
    }


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

    public void setVideoDate(String videoDate) {
        this.videoDate = videoDate;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

 

Step 5 Finely Open you Main_Activity.java Class and follow below.

in your main activity java class you and find the recycler view id and make a method for parser the date to list and set data to RecyclerviewAdapter class.

package com.lcodeplayon.recyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

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

public class MainActivity extends AppCompatActivity {

    RecyclerView RecyclerView;
    RecyclerViewAdapter videoAdupter;

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

        FindViewById();
    }

    public void FindViewById(){

        RecyclerView = findViewById(R.id.RecyclerView);

        List<VideoDataItem> data = new ArrayList<>();

        for(int i=0; i<5; i++ ){
            VideoDataItem dataItem =  new  VideoDataItem();
            dataItem.setTitle("Codeplayon");
            dataItem.setImage("https://www.codeplayon.com/wp-content/uploads/2018/10/logo-8.png");
            dataItem.setUrl("https://www.codeplayon.com/");
            dataItem.setDescription("Codeplayon Learn share and explore ");
            dataItem.setVideoDate("08/24/2023");


            data.add(dataItem);
        }

        OnPostExecute(data);

    }



    public void OnPostExecute(List<VideoDataItem> data){


        videoAdupter = new RecyclerViewAdapter(this, data);
        RecyclerView.setAdapter(videoAdupter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,1);
        RecyclerView.setLayoutManager(gridLayoutManager);
//            recyclerView.setLayoutManager(new LinearLayoutManager(Event_Activity.this));
        RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }
}

 

Recyclerview row item selected color change android

myHolder.VideoCardViw.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View view) {
        index = myHolder.getAdapterPosition();
        notifyDataSetChanged();
    }
});
if(index== position){
    myHolder.LinverLayout.setBackgroundColor(Color.parseColor("#FFEB3B"));
} else {
    myHolder.LinverLayout.setBackgroundColor(Color.parseColor("#E3E4E6"));
}

 

Read More Tutorial