RecyclerView using CardView

Published Jul 14, 2017Last updated Sep 11, 2017
RecyclerView using CardView

In today's article, I will show you how to create RecyclerView using CardView and how to hide the toolbar when scrolling down.

Android RecyclerView and Android CardView was introduced with Material Design in Android Lollipop.

Android RecyclerView is a more advanced, powerful, and flexible version of the ListView. Android RecyclerView is similar to ListView except it forces us to use RecyclerView. ViewHolder class to hold the elements which is not a compulsion in ListView.

The CardView widget can be used to create simple cards. It can also support rounded edges and elevation. In this tutorial we are going to create an Android app with basic RecyclerView and CardView widgets.

Create a Android Project

Open Android Studio and create a new project.
The first thing you have to do is to go to build.gradle and add the following lines inside the dependencies tag.

compile 'com.android.support:appcompat-v7:25.0.3'
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'

Sync the project andthe dependencies will be downloaded.
Create an activity.
mainactivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.example.admin.hidetoolbaronscroll.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="?attr/actionBarSize"
        android:clipToPadding="false"/>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"/>

</RelativeLayout>

Now create one more layout resource file cardview_layout.xml for the RecyclerView adapter.

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"

    card_view:cardCornerRadius="4dp">
<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"

    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/itemTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:layout_gravity="center"
        android:layout_marginLeft="60dp"
        android:padding="8dp"
        android:textColor="#000"
        android:text="HappyCoding"
        style="@style/Base.TextAppearance.AppCompat.Body2"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/images"
        android:id="@+id/imageview"

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

Now we will create a model for our ListItem in the layout. Start by creating a new Java class named ModelItem and write the following code:

public class ModelItem {
    String id;
    String name;
    int profilepic;

    public ModelItem(String id, String name, int profilepic) {
        this.id = id;
        this.name = name;
        this.profilepic = profilepic;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getProfilepic() {
        return profilepic;
    }

    public void setProfilepic(int profilepic) {
        this.profilepic = profilepic;
    }
}

Before implementing RecyclerView in Activity, we need to create an adapter to allow RecyclerView to send data to individual list items.

The Adapter acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

RecyclerAdapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private ArrayList<ModelItem> requestItems;
    private Context context;

    public RecyclerAdapter(Context context, ArrayList<ModelItem> requestItems) {
        this.context = context;
        this.requestItems = requestItems;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView textView;
        public ImageView imageView;




        public ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.itemTextView);
            imageView = (ImageView) itemView.findViewById(R.id.imageview);

        }

        @Override
        public void onClick(View v) {

        }
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
        return new ViewHolder(view);

    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
        final ModelItem modelItem = requestItems.get(position);

        holder.textView.setText(modelItem.getName());


        holder.imageView.setImageResource(modelItem.getProfilepic());

    }



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


}

Now, to hide the toolbar when scrolling down, we have to tell the RecyclerView to use a MyScrollListener implementation, which must be implemented in onMoved(). Add the following code to MainActivity after expanding RecyclerView.

recyclerView.setOnScrollListener(new MyScrollListeneView(this) {
    @Override
    public void onMoved(int distance) {
        toolbar.setTranslationY(-distance);
    }
});

In this segment, we monitor the current toolbar position by using the toolbarOffset variable and decide whether to hide the toolbar or not by calling the onMoved()method. onMoved() is an abstract method that must be overridden when MyScrollListener is implemented.

MyScrollListeneView.java

package com.example.admin.hidetoolbaronscroll;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.RecyclerView;




    public abstract class MyScrollListeneView extends RecyclerView.OnScrollListener {

        private int toolbarOffset = 0;
        private int toolbarHeight;

        public MyScrollListeneView(Context context) {
            int[] actionBarAttr = new int[] { android.R.attr.actionBarSize };
            TypedArray a = context.obtainStyledAttributes(actionBarAttr);
            toolbarHeight = (int) a.getDimension(0, 0) + 10;
            a.recycle();
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            clipToolbarOffset();
            onMoved(toolbarOffset);

            if((toolbarOffset < toolbarHeight && dy>0) || (toolbarOffset > 0 && dy<0)) {
                toolbarOffset += dy;
            }
        }

        private void clipToolbarOffset() {
            if(toolbarOffset > toolbarHeight) {
                toolbarOffset = toolbarHeight;
            } else if(toolbarOffset < 0) {
                toolbarOffset = 0;
            }
        }

        public abstract void onMoved(int distance);
    }

AAEAAQAAAAAAAAq3AAAAJDFjZmQwYjZiLWNkY2QtNDYzMC1hZWVhLWY1ZDBmY2NmMzkyMg.png

Finally, write the following codew inside MainActivity.java.

package com.example.admin.hidetoolbaronscroll;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;

import com.example.admin.hidetoolbaronscroll.adapter.RecyclerAdapter;
import com.example.admin.hidetoolbaronscroll.model.ModelItem;

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

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerAdapter recyclerAdapter;
    private ArrayList<ModelItem> requestsItemArrayList;
    LinearLayoutManager linearLayoutManager;
    private Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findviewById();
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle(getString(R.string.app_name));
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));




    }
    private void setListValues(){

        requestsItemArrayList = new ArrayList<ModelItem>();
        requestsItemArrayList.add(new ModelItem("1", "Happy Coding", R.drawable.images));
        requestsItemArrayList.add(new ModelItem("1", "Happy Coding", R.drawable.images));
        requestsItemArrayList.add(new ModelItem("1", "Happy Coding", R.drawable.images));
        requestsItemArrayList.add(new ModelItem("1", "Happy Coding", R.drawable.images));
        requestsItemArrayList.add(new ModelItem("1", "Happy Coding", R.drawable.images));

        recyclerAdapter = new RecyclerAdapter(this,requestsItemArrayList);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(recyclerAdapter);

        recyclerView.setOnScrollListener(new MyScrollListeneView(this) {
            @Override
            public void onMoved(int distance) {
                toolbar.setTranslationY(-distance);
            }
        });


    }

    private void findviewById(){
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(MainActivity.this);

    }
    @Override
    public void onResume() {
        super.onResume();
        setListValues();
    }
}

Download Source Code

For Code Reference:https://github.com/rohan5576/HideToolbarOnScroll

I hope this article provided useful information about the RecyclerView by using CardView. If you have any queries please leave a comment for me!

AAEAAQAAAAAAAAugAAAAJGQ2MzRmMDQ1LTM5M2EtNDdmNC04NDk2LTQ2ZWFmZTkyNzU5NA.png

THANK YOU!!!!

Discover and read more posts from Rohan Lodhi
get started
Enjoy this post?

Leave a like and comment for Rohan

2
2