Working with Android Recyclerview and CardView example




Android recyclerview and cardview
The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events.


We all know how to use ListView in our app and we know if we want to increase the ListView performances we can use a pattern called ViewHolder. This pattern consists of a simple class that holds the references to the UI components for each row in the ListView.

This pattern avoids looking up the UI components all the time the system shows a row in the list. Even if this pattern introduces some benefits, we can implement the ListView without using it at all. RecyclerView forces us to use the ViewHolder pattern.
The RecyclerView class simplifies the display and handling of large data sets by providing:
  • Layout managers for positioning items
  • Default animations for common item operations, such as removal or addition of items
You also have the flexibility to define custom layout managers and animations for RecyclerView widgets.
Figure 1. The RecyclerView widget.
To use the RecyclerView widget, you have to specify an adapter and a layout manager.

Working with CardView

CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners.

To create a card with a shadow, use the card_view:cardElevation attribute. CardView uses real elevation and dynamic shadows on Android 5.0 (API level 21) and above and falls back to a programmatic shadow implementation on earlier versions.

Lets get Started!
We’ll start this by creating a new project and applying the material theme.
1. In Android Studio, go to File -> New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed.

Adding Dependencies

2. Open build.gradle and add android design support library  com.android.support:design:23.2.1 and other dependencies.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
}
Open colors.xml located under res -> values and add the below color values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#1A4B9C</color>
    <color name="colorPrimaryDark">#003791</color>
    <color name="colorAccent">#FF4081</color>
    <color name="textcolor">#000000</color>
</resources>
Open styles.xml located res -> values and add below styles. The styles defined in this styles.xml are common to all the android versions.
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>



Finally open AndroidManifest.xml and modify the theme to our requirement
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidxu.com.menucard">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="androidxu.com.menucard.ListViewActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Now we have our app material ready. So let’s start adding and building the layout file to demonstrate horizontal and vertical listview
Create and open Open the layout file of item_horizontal_list activity (res->item_horizontal_list.xml) and add below layout code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="210dp"
    android:layout_height="wrap_content"
    android:layout_marginRight="5dp">

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

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

            android:adjustViewBounds="true"

            android:src="@drawable/mountain" />

        <TextView
            android:id="@+id/txtview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/lorem_ipsum" />

    </LinearLayout>
</android.support.v7.widget.CardView>
Create and open Open the layout file of item_vertical_list activity (res > item_vertical_list.xml) and add below layout code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/image"
            android:layout_width="100dp"
            android:layout_height="80dp"
            android:contentDescription="@string/app_name"
            android:padding="5dp"
            android:src="@drawable/mountain" />

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/image"
            android:text="@string/lorem_ipsum"
            android:textStyle="bold"
            android:layout_marginLeft="5dp"
            android:textColor="@color/textcolor" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/image"
            android:layout_below="@+id/text"
            android:layout_marginLeft="5dp"
            android:layout_toEndOf="@+id/image" />

    </RelativeLayout>

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


Open the layout folder  and create a blank layout file which hold the layout of recyclerview
Add a Linearalayout which binds both the list in a scrollview  by creating a new blank layout file activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:scrollbars="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="20dp"
        android:text="Recommended for You"
        android:textStyle="bold" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/horizontal_recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:textColor="@color/colorPrimaryDark"
        android:text="Top Deals of the Day"
        android:textStyle="bold" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyle_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
</ScrollView>

Create a HorizontalListAdapter.java which will extend the recylerview to hold the recyclerview .
package androidxu.com.menucard;

import android.app.Activity;
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.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

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

    private Activity activity;
    int[] images= {R.drawable.prawan,R.drawable.awadhi_lucknow_biryani,R.drawable.eggwraps,
            R.drawable.chips,R.drawable.mayonnaise,R.drawable.cmp,R.drawable.mixvegwrap};
    String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};


    public HorizontalListAdapter(Activity activity) {
        this.activity = activity;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        LayoutInflater inflater = activity.getLayoutInflater();
        View view = inflater.inflate(R.layout.item_horizontal_list, viewGroup, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(HorizontalListAdapter.ViewHolder viewHolder, final int position) {
        viewHolder.imageView.setImageResource(images[position]);
        viewHolder.txtview.setText(food_items[position].toUpperCase());

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

                Toast.makeText(activity, "Position clicked: " + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    /**
     * View holder to display each RecylerView item
     */
    protected class ViewHolder extends RecyclerView.ViewHolder {

        private LinearLayout linearLayout;
        private ImageView imageView;
        private TextView txtview;


        public ViewHolder(View view) {
            super(view);
            imageView = (ImageView) view.findViewById(R.id.imageview);
            txtview = (TextView) view.findViewById(R.id.txtview);
            linearLayout = (LinearLayout) view.findViewById(R.id.layout);
        }
    }
}

Similarly,Create a VerticalListAdapter.java which will extend the vertical recylerview to hold the recyclerview .
package androidxu.com.menucard;

import android.app.Activity;
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.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class VerticalListAdapter extends RecyclerView.Adapter {

    private Activity activity;

    public VerticalListAdapter(Activity activity) {
        this.activity = activity;
    }
    int[] images= {R.drawable.prawan,R.drawable.awadhi_lucknow_biryani,R.drawable.eggwraps,
            R.drawable.chips,R.drawable.mayonnaise,R.drawable.cmp,R.drawable.mixvegwrap};
    String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
    String[] cost={"Rs 200","Rs 300","Rs 150","R 320","Rs 450","Rs 120","Rs 380"};
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = activity.getLayoutInflater();
        View view = inflater.inflate(R.layout.item_recycler_view, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
       // if ((position + 1) % 2 == 0) {
            viewHolder.imageView.setImageResource(images[position]);
             viewHolder.txtview.setText(food_items[position].toUpperCase());
        viewHolder.txtCost.setText("Cost Per Person "+cost[position]);
       // } else {
          //  viewHolder.imageView.setImageResource(R.drawable.awadhi_lucknow_biryani);
        //}
        viewHolder.container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(activity, "Position: " + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    /**
     * View holder to display each RecylerView item
     */
    protected class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView txtview;
        private TextView txtCost;
        private RelativeLayout container;

        public ViewHolder(View view) {
            super(view);
            imageView = (ImageView) view.findViewById(R.id.image);
            txtview = (TextView) view.findViewById(R.id.text);
            txtCost= (TextView) view.findViewById(R.id.textView);
            container = (RelativeLayout) view.findViewById(R.id.container);
        }

    }
}


Now add both the view and bind the adapters in ListViewActivity.java
package androidxu.com.menucard;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class ListViewActivity extends AppCompatActivity {

    private RecyclerView horizontalList;
    private RecyclerView verticalList;
    private HorizontalListAdapter horizontalAdapter;
    private VerticalListAdapter verticalAdapter;

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

        horizontalList = (RecyclerView)findViewById(R.id.horizontal_recycler);
        verticalList = (RecyclerView)findViewById(R.id.recyle_view);

       // horizontalList.setHasFixedSize(true);
        //verticalList.setHasFixedSize(true);

        //set horizontal LinearLayout as layout manager to creating horizontal list view
        LinearLayoutManager horizontalManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        horizontalList.setLayoutManager(horizontalManager);
        horizontalAdapter = new HorizontalListAdapter(this);
        horizontalList.setAdapter(horizontalAdapter);

        //set vertical LinearLayout as layout manager for vertial listview
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        verticalList.setLayoutManager(layoutManager);
        verticalAdapter = new VerticalListAdapter(this);
        verticalList.setAdapter(verticalAdapter);
    }
}
Run the App
Android recyclerview and cardview

Comments

bacasoft said…
Hi, i tried this tutorial and it's not showing nothing in the cardview/recycler view. it comes empty, any help?
kwesi sefam said…
Please how can i download the project

Popular posts from this blog

Android Bottom Navigation Bar tutorial with Fragments

Pandas in Python for Data Analysis with Example(Step-by-Step guide)

Pandas in Python - Dataframe Tutorial(With examples)