Android Simple RecyclerView Widget Example

recyclerview RecyclerView is a new widget in Android L Developer Preview support library. RecyclerView is a more advanced and flexible than ListView This widgets have material design style by default. Use RecyclerView widget when you have lists that change dynamically.

 

 

 

Objectives:

  • How to add RecyclerView widget to your Android app?
  • How to run an app with RecyclerView on your Emulator?

Environment & Tools:

  • Eclipse ADT
  • AVD
    • Device: Nexus 5
    • Target: Android 4.4.2 – API Level 19

About This Example:

We will use RecyclerView to show a list of items. Each item is an icon “image” with a title. To use the RecyclerView widget, you have to specify:

  • an Adapter: extend the RecyclerView.Adapter class
  • a LayoutManager: shows the items in a vertical or horizontal scrolling list. To create a custom layout, you extend the RecyclerView.LayoutManager

android-recyclerview-item-layout

( 1 ) SDK Manager

  • Select the latest Android SDK Tools, Platform-tools, and Build-tools.

This example uses below SDK Tools, Platform-tools & Build-tools.

android-latest-tools

  • Select latest Android Support Library & Android Support Repository.

This example uses below Android Support Library & Android Support Repository.

android-latest-support

( 2 ) recyclerview-v7 Support Library

  • After updating Android Support Repository from SDK Manager go to ..\sdk\extras\android\m2repository\com\android\support\recyclerview-v7\21.0.0-rc1
  • Unzip recyclerview-v7-21.0.0-rc1.aar
  • After unzipping recyclerview-v7-21.0.0-rc1.aar you will get classes.jar
  • You will add this classes.jar file to your Android app under /lib folder

( 3 ) Create a New Android App

  • Application Name: RecyclerView
  • Project Name: android-recyclerview
  • Package Name: com.hmkcode.android.recyclerview
  • Minimum SDK: API 8: Android 2.2
  • Target SDK: API 19: Android 4.4 (Kitkat)
  • Compile: API 19: Android 4.4 (Kitkat)
  • Click Next
  • Select BlankActivity
  • Click Finish

Note: You need to import appcompat_v7 library if it is not important by default.

Eventually you need to add the following files to your application:

  • Java Classes
    1. MainActivity.java
    2. MyAdapter.java
    3. ItemData.java
  • Jar File
    1. classes.jar “jar file we got from step 2″
  • Layout
    1. activity_main.xml
    2. item_layout.xml

android-recyclerview-app-files

( 4 ) Main Activity Layout

We have the below view inside the layout file

  • RelativeLayout
  • android.support.v7.widget.RecyclerView
  • /res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    tools:context="com.hmkcode.android.recyclerview.MainActivity" >

    <android.support.v7.widget.RecyclerView
	    xmlns:android="http://schemas.android.com/apk/res/android"
	    xmlns:tools="http://schemas.android.com/tools"
	    android:id="@+id/recyclerView"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"
	    tools:context=".MainActivity"
    />
</RelativeLayout>

( 5 ) Item View Layout

The layout that will be used for each item in the RecyclerView contains one ImageView and one TextView.

  • /res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="@drawable/border"
    >
    
     <!-- icon -->
     <ImageView
         android:id="@+id/item_icon"
         android:layout_width="64dp"
         android:layout_height="64dp"
         android:layout_alignParentLeft="true"
         android:layout_marginLeft="8dp"
         android:layout_marginRight="8dp"
         android:layout_marginTop="1dp"
         android:layout_marginBottom="1dp"
         android:contentDescription="icon"
         android:src="@drawable/ic_launcher"
     />
    
    <!-- title -->
    <TextView
         android:id="@+id/item_title"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_toRightOf="@+id/item_icon"
         android:layout_alignBaseline="@+id/item_icon"
         android:textColor="@android:color/darker_gray"
          android:layout_marginLeft="8dp"
         android:layout_marginRight="8dp"
         android:layout_marginTop="8dp"
         android:textSize="22dp" />

</RelativeLayout>

( 6 ) Item Model “Data”

This class shall hold data needed by each item view. E.g. image location and title text.

  • /src/com/hmkcode/android/recyclerview/ItemData.java
package com.hmkcode.android.recyclerview;

public class ItemData {


	private String title;
	private int imageUrl;
	
	public ItemData(String title,int imageUrl){
		
		this.title = title;
		this.imageUrl = imageUrl;
	}
    // getters & setters
}

( 7 ) RecyclerView Adapter

This is the main step in implementing RecyclerView.

For each item

  1. Inflate item_layout
  2. Create a ViewHolder
  3. Bind the view “ViewHolder” with data “ItemData”
  • /src/com/hmkcode/android/recyclerview/MyAdapter.java
package com.hmkcode.android.recyclerview;

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;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private ItemData[] itemsData;

    public MyAdapter(ItemData[] itemsData) {
        this.itemsData = itemsData;
    }
    
    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View itemLayoutView = LayoutInflater.from(parent.getContext())
                               .inflate(R.layout.item_layout, null);

        // create ViewHolder
       
        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        
    	// - get data from your itemsData at this position
        // - replace the contents of the view with that itemsData
    	
    	viewHolder.txtViewTitle.setText(itemsData[position].getTitle());
    	viewHolder.imgViewIcon.setImageResource(itemsData[position].getImageUrl());


    }
    
    // inner class to hold a reference to each item of RecyclerView 
    public static class ViewHolder extends RecyclerView.ViewHolder {
       
    	public TextView txtViewTitle;
        public ImageView imgViewIcon;
        
        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);
            txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
            imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
        }
    }


    // Return the size of your itemsData (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return itemsData.length;
    }
}

( 8 ) MainActivity

  • /src/com/hmkcode/android/recyclerview/MainActivity.java
package com.hmkcode.android.recyclerview;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 1. get a reference to recyclerView 
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        
        // this is data fro recycler view
        ItemData itemsData[] = { new ItemData("Help",R.drawable.help),
        		new ItemData("Delete",R.drawable.content_discard),
 		        new ItemData("Cloud",R.drawable.collections_cloud),
 		        new ItemData("Favorite",R.drawable.rating_favorite),
        		new ItemData("Like",R.drawable.rating_good),
        		new ItemData("Rating",R.drawable.rating_important)};
       
        // 2. set layoutManger
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 3. create an adapter 
        MyAdapter mAdapter = new MyAdapter(itemsData);
        // 4. set adapter
        recyclerView.setAdapter(mAdapter);
        // 5. set item animator to DefaultAnimator
        recyclerView.setItemAnimator(new DefaultItemAnimator());

    }
}

( 9 ) Deploy & Run

android-recyclerview

Source Code @ GitHub

Leave a Reply