RecyclerView in Android Studio – Part 1

Datetime:2016-08-22 23:17:33          Topic: Android Studio           Share

What is RecyclerView?

RecyclerView is advanced version of ListView . It is designed to work with large scale of data with better performance and memory management. Combination of CardView and RecyclerView will give you more flexibility for designing complex views.

RecyclerView v/s ListView

Feature RecyclerView ListView
ViewHolder pattern In-built. Compulsory to implement Explicit. Not necessary to implement compulsory
Animation Large amount of animations Limited number of animations
Performance Comparatively high Comparatively less
Multipurpose Yes. You can use RecyclerView for ListView, GridView and Staggered View No. You require to use different view like GridView
Memory Usage Comparatively less Comparatively high

Let start with RecyclerView in project step by step.

Step 1

Create a new project from File -> New project and fill all necessary details and select “Blank Activity”.

Step 2

Android Studio has introduce a new way to integrate dependency integration in “Gradle”. So to use RecyclerView in your project you require to add gradle dependency.

gradle

Open build.gradle file and add below libraries in “dependency” tag.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
}

This will add all necessary library files in our project and give a dependency on that. It will download binaries from server of provided version “23.1.1”

Step 3

You are done with dependency integration. Now add RecyclerView in your layout.

When you create application with “Blank Activity”, it will create MainActivity.java and activity_main.xml layout file. Open layout file and add view inside.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="chintan.rathod.recyclerviewsample.MainActivity">

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

</RelativeLayout>

In above code, we did 4 things.

– We took reference of “RecyclerView” from “support v7” library and declare it

– We gave “id” to declared “RecyclerView”

– we set “height” and “width” of it

– We set “scrollbars” to vertical mode

Step 4

Two main things require when you are working with list.

1. Entity which will bind to your View

2. Item layout file which will be used to design your item.

Step 4.1

So first we will create a class file called Item.java and define necessary parameters in it.

public class Item {

    private String description;

    public Item(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

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

Step 4.2

Create a new layout file called item_layout.xml to design item layout for our list.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

In above layout we took parent as LinearLayout and add TextView as its child. When we see in design, it will look like

Item layout output

Step 5

In RecyclerView , it is mandatory to define ViewHolde . So to create it, create a new class file called ItemHolder .

Holder class are those which are defined with layout views used in items. In our case it is only single TextView .

public class ItemHolder extends RecyclerView.ViewHolder {

    public TextView txtDescription;

    public ItemHolder(View view) {
        super(view);
        txtDescription = (TextView) view.findViewById(R.id.txtDescription);
    }
}

Here, we require to understand functionality and importance of RecyclerView.Holder .

If you noticed, we declared a class and we are creating sub class of RecyclerView.ViewHolder by extending it.

public class ItemHolder extends RecyclerView.ViewHolder

As we created sub class, we require to pass our newly created object to super class by calling super(view) . This will pass our view object to parent class.

Rest thing are like we are doing for finding view and assigning to widget.

txtDescription = (TextView) view.findViewById(R.id.txtDescription);

This will search for id R.id.txtDescription from provided view object and convert it to view object and assigns to provided object “txtDescription”

Step 6

All we did is just preparation for things get ready to use in adapter. But actual use will be in next Adapter which we are going to define.

Create ItemAdapter.java class by extending RecyclerView.Adapter like below.

public class ItemAdapter extends RecyclerView.Adapter<ItemHolder> {

    private List<Item> itemList;

    public ItemAdapter(List<Item> itemList) {
        this.itemList = itemList;
    }

    @Override
    public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_layout, parent, false);

        return new ItemHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ItemHolder holder, int position) {
        Item item = itemList.get(position);
        holder.txtDescription.setText(item.getDescription());
    }

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

6.1 Class declaration

public class ItemAdapter extends RecyclerView.Adapter<ItemHolder>

When you write this like, application will create a sub class of “RecyclerView.Adapter<>“. Here, you require to pass “ViewHolder” you have created previously in “Step – 5”

6.2 Constructor

public ItemAdapter(List<Item> itemList) {
    this.itemList = itemList;
}

You require to create a constructor to pass your list data so that adapter can work on it. In this example, we are passing list of “item” class which we created in “Step 4”. Simply create a file “itemList” in adapter and assign list which is passed in constructor.

6.3 ViewHolder mapping

@Override 
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        
	View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_layout, parent, false);

       return new ItemHolder(itemView);
}

This is override method of Adapter class. It has main functionality of binding view with Holder. So in this method we need to create view by inflating layout and pass that newly created view object in our ItemHolder constructor. Rest of work will be taken care by our “ItemHolder” class. (See Step 5)

6.4 Binding Holder with item

@Override
public void onBindViewHolder(ItemHolder holder, int position) {
    Item item = itemList.get(position);
    holder.txtDescription.setText(item.getDescription());
}

As described in 6.3, we created ItemHolder which will be returned in this method as argument. So we need to give data to bind them. As you can see in this method, we are taking item from list and setting text to “txtDescription” object.

6.5. Counting list item

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

This method will tell adapter size of item list. Whatever count you are passing here, adapter will create items for RecyclerView and push them to it. Make sure you are passing proper size of list as in previous step you are taking object from that list. If you pass wrong argument, you will encounter an exception for IndexOutOfBoundsException .

Step 7

This is final step to assign adapter to RecyclerView. So open your MainActivity.java file and paste below code.

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

    private ItemAdapter itemAdapter;

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

        ArrayList<Item> itemList = new ArrayList<>();

        fillDummyData(itemList);

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

        itemAdapter = new ItemAdapter(itemList);
        RecyclerView.LayoutManager mLayoutManager = 
		new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(itemAdapter);
    }

    private void fillDummyData(ArrayList<Item> itemList) {
        for(int count = 1; count< 20; count++){
            Item item = new Item("Item "+ count);
            itemList.add(item);
        }
    }
}

We first need to first take view from layout and assign it to object. Then we will create an object of “ItemAdapter” with dummy data. We already prepared dummy data with help of “fillDummyData” method.

Step 8

Run your application. Output will be like below.

Download Code

Source code for this article is availablehere.

0 0 0 0 0 0

You may also like to read

Develop apps faster using Data Binding – Part 4 Google has been pushing updates to existing tools and making the life of android developers easier. They also have been releasing new libraries and AP...

Customizing TextInputLayout – Part 2 In previous article Customizing TextInputLayout - Part 1, we learnt how to customize TextInputLayout and how to apply hint color to it. Going t...

Develop apps faster using Data Binding – Par... Google has been pushing updates to existing tools and making the life of android developers easier. They also have been releasing new libraries and AP...

Secret Codes For Android Mobile Phones Every mobile device has some secret codes which can be very much useful to get information if we are aware of it. 1. Complete Information Abo...

Views: 1





About List