[Android] RecyclerView in Android

Hello everyone, long long time no blog, in this article I will introduce and teach you the basics of using the Android RecyclerView.

What is RecyclerView

RecyclerView is a new View in android like ListView but very much stronger.
RecyclerView allows us to load more data ListView, claw smoother, better effect and supports diverse layout of the elements in the list.

Use RecyclerView in Eclipse

Do not know your machine to use is reliable Android Studio not yet smoothly with “wife” her then it can ignite when enabled Android Studio. So I used Eclipse is enough. However, most of the guides now are guidelines you should do on your Android Studio adds this to what you have “conjuncture” like her.

You go to the directory where the sdk and heart to directory: sdkextrasandroidm2repositorycomandroidsupportrecyclerview-v722.1.1 (the directory 22.1.1 sdk his version used, Your longer does the user to that directory) and you will see the file recyclerview-v7-22.1.1.aar, you copy it to another location, change its name recyclerview-v7-22.1.1.zip (If using Windows, do not forget to show its tail up) and extract you will find 1 file classes.jar, this is our library files needed. You can rename it for catchy, change it yourself recyclerview.jar. You copy it into the folder lib the project is finished.

Use RecyclerView in Android Studio

If you use Android, the studio said earth station, I have not verified that you can add the following to the file Gradle:

compile 'com.android.support:recyclerview-v7:21.0.+'

Code generated by RecyclerView List

First you create a project as usual, finished we start code…

XML interface

First lag interface 1 element in the list include text and 1 delete button. File item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingLeft="8dp"
    android:paddingRight="8dp" >

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1" />

    <ImageButton
        android:id="@+id/btn_delete"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:src="@drawable/ic_delete" />

</LinearLayout>

In the code above

Then create interfaces consisting Activity 1 EditText enter text, 1 button Add, and a display list RecyclerView. File activity_main.xml

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

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

        <EditText
            android:id="@+id/edit_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="name" />

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add" />
    </LinearLayout>

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

</LinearLayout>

Code handle java

First we create a class that contains data Data 1 element, in this example named himself alone. FIle Data.java

package cachhoc.net.samplerecyclerview;

public class Data {
	private String name;

	public Data(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

}

Follow, like when customize ListView, we need to create 1 separate adapter. And here, too, we create 1 adapter for Recyclerview. File CustomRecyclerAdapter.java

package cachhoc.net.samplerecyclerview;

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

import cachhoc.net.samplerecyclerview.CustomRecyclerAdapter.RecyclerViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

public class CustomRecyclerAdapter extends
		RecyclerView.Adapter<RecyclerViewHolder> {

	private List<Data> listData = new ArrayList<Data>();

	public CustomRecyclerAdapter(List<Data> listData) {
		this.listData = listData;
	}

	public void updateList(List<Data> data) {
		listData = data;
		notifyDataSetChanged();
	}

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

	@Override
	public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup,
			int position) {
		LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
		View itemView = inflater.inflate(R.layout.item, viewGroup, false);
		return new RecyclerViewHolder(itemView);
	}

	@Override
	public void onBindViewHolder(RecyclerViewHolder viewHolder, int position) {
		viewHolder.tvName.setText(listData.get(position).getName());
	}

	public void addItem(int position, Data data) {
		listData.add(position, data);
		notifyItemInserted(position);
	}

	public void removeItem(int position) {
		listData.remove(position);
		notifyItemRemoved(position);
	}

	/**
	 * ViewHolder for item view of list
	 * */

	public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
			OnClickListener {

		public TextView tvName;
		public ImageButton btnDelete;

		public RecyclerViewHolder(View itemView) {
			super(itemView);
			tvName = (TextView) itemView.findViewById(R.id.tv_name);
			btnDelete = (ImageButton) itemView.findViewById(R.id.btn_delete);

			// set listener for button delete
			btnDelete.setOnClickListener(this);
		}

		// remove item when click button delete
		@Override
		public void onClick(View v) {
			removeItem(getAdapterPosition());
		}
	}

}

In the code above you a little attention, Other ListView it that.
Method onCreateViewHolder getView have similar functionality when using ListView, it is to seek to interface 1 element, is item.xml built above but returned when we returned RecyclerViewHolder.

Method onBindViewHolder called to set the values ​​in the elements.

RecyclerViewHolder was 1 class contains the attributes that an element has (text name và button delete). In RecyclerViewHolder you also note that we start the event for the delete button here and not captured in the capture event onCreateViewHolder because we need to know location (position) through methods getAdapterPosition rather than captured in onCreateViewHolder will lead to errors.

Finally write code for MainActivity. This one's easy rùi. File MainActivity.java

package cachhoc.net.samplerecyclerview;

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

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {

	private RecyclerView recyclerView;
	private CustomRecyclerAdapter adapter;
	private RecyclerView.LayoutManager layoutManager;

	private EditText editName;

	private List<Data> listData = new ArrayList<Data>();

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

		// connect views.
		editName = (EditText) findViewById(R.id.edit_name);
		recyclerView = (RecyclerView) findViewById(R.id.recycler);

		// If the size of views will not change as the data changes.
		recyclerView.setHasFixedSize(true);

		// Setting the LayoutManager.
		layoutManager = new LinearLayoutManager(this);
		recyclerView.setLayoutManager(layoutManager);

		// Setting the adapter.
		adapter = new CustomRecyclerAdapter(listData);
		recyclerView.setAdapter(adapter);

		// set listener for button add
		((Button) findViewById(R.id.btn_add)).setOnClickListener(this);
	}

	// Called when add button is clicked.
	public void addItem() {

		// get data.
		Data dataToAdd = new Data(editName.getText().toString());

		// Update adapter.
		adapter.addItem(listData.size(), dataToAdd);
	}

	@Override
	public void onClick(View v) {
		addItem();
	}
}

You can download project (implementation on eclipse) Sample Recyclerview