Android RecyclerView with Animation Tutorial

In this tutorial, you will learn how to use RecyclerView with animation in Android Application.

 
 

Introduction

RecyclerView is more advanced and flexible and efficient version of ListView with large data set of views that can be scrolled and recycled.

In this tutorial, we will create a list of items and display it as list using RecyclerView. We will use animation, when scrolling the recyclerview from bottom to top.

 




Adding Support Library

To use the RecyclerView in your project, you need to add recycler view support library to your project. Also, we will display text and image in the list. To display image, add the Picasso library in dependencies. Open your build.gradle (app) file and add library in the dependencies.

 

dependencies {
   ....
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

 

Add RecyclerView to the layout file

We need to add a RecyclerView to show set of data. Add the following code in your activity.xml file:

 

<?xml version="1.0" encoding="utf-8"?>
<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="app.androidrecyclerview.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:layout_marginTop="8dp" />
</RelativeLayout>

 

Create a custom row Layout

Create a file named item_list.xml to show text and image in the recyclerview and add the following code to it:

<?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="wrap_content"
    android:padding="20dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#11000000"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="18sp"/>

</LinearLayout>

 

Initialize the RecyclerView

To use the feature of RecyclerView, you need to initialize RecyclerView in the MainActivity.java file

 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.list);
    }
}

 

If you are sure, that the size of RecyclerView won’t change then you can add the following code to improve performance:

 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.list);
      mRecyclerView.setHasFixedSize(true);
    }
}

 

Attach the LayoutManager

A RecyclerView needs a LayoutManager to manage the positioning of its items. As user scrolls view, the Layout Manager determines when new child view will add and when the old child view will detect and delete. You can attach your LayoutManager by extending RecyclerView.LayoutManager

 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.list);
      mRecyclerView.setHasFixedSize(true);
      mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

 

Creating an ArrayList

Now, we need a set of values that will be provided as data source to the recyclerview. We will use ArrayList to provide the data to list.

 

public class MainActivity extends AppCompatActivity {

    private List<String> list = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.list);
      mRecyclerView.setHasFixedSize(true);
      mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
      arrayList();

    }

    public void arrayList(){
        for (int i = 0; i< 20; i++){
            list.add("This is row of number "+ i);
        }
    }
}

 

Creating RecyclerView Adapter class

The RecyclerView.Adapter class is similar to Adapter class of listview but with ViewHolder class improve performance of RecyclerView.Adapter class.

 

Now, we need to attach textview and image to show with recyclerview. We will create a custom Adapter class and extend Adapter class with RecyclerView.Adapter. This adapter follows the view holder design pattern. Which means we need to define a custom class that extends RecyclerView.ViewHolder.

 

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

    // initializes textview and imageview to be used by RecyclerView.
    public static class ViewHolder extends RecyclerView.ViewHolder {

       public TextView textView;
       public ImageView imageView;

       public ViewHolder(View view) {
           super(view);

           textView = (TextView) view.findViewById(R.id.text);
           imageView = (ImageView) view.findViewById(R.id.image);
        }
    }
}

 

Creating constructor

We will add constructor in the Adapter class. In this method, we will initialize the data that display in the recyclerView.

 

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

    private List<String> list ;
    public Context context;
    ViewHolder viewHolder;

    public Adapter(List<String> list, Context context) {
        this.context = context;
        this.list = list;
    }

    // initializes textview and imageview to be used by RecyclerView.
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public ImageView imageView;

        public ViewHolder(View view) {
            super(view);

            textView = (TextView) view.findViewById(R.id.text);
            imageView = (ImageView) view.findViewById(R.id.image);
        }
    }
}

 

Creating a getItemCount()

We will create a getItemCount() method in the Adapter. This method return the number of items present in the data.

 

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

    private List<String> list ;
    public Context context;
    ViewHolder viewHolder;

    public Adapter(List<String> list, Context context) {

        this.list = list;
        this.context = context;
    }

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

    // initializes textview and imageview to be used by RecyclerView.
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public ImageView imageView;

        public ViewHolder(View view) {
            super(view);

            textView = (TextView) view.findViewById(R.id.text);
            imageView = (ImageView) view.findViewById(R.id.image);
        }
    }
}

 

Creating a OnCreateViewHolder() Method

Next, use the onCreateViewHolder() method. This method is called when the custom ViewHolder needs to be initialized. This method is inflating the layout using LayoutInflater and passing the output to the constructor of the custom ViewHolder.

 

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

    private List<String> list ;
    public Context context;
    ViewHolder viewHolder;

    public Adapter(List<String> list, Context context) {

        this.list = list;
        this.context = context;
    }

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

    @Override
    public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                 int viewType) {
        //Inflate the layout, initialize the View Holder
        View itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_list, null);

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

    // initializes textview and imageview to be used by RecyclerView.
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public ImageView imageView;

        public ViewHolder(View view) {
            super(view);

            textView = (TextView) view.findViewById(R.id.text);
            imageView = (ImageView) view.findViewById(R.id.image);
        }
    }
}

 

Creating a onBindViewHolder() Method

We will use onBindViewHolder() to display the data on a specific position in RecyclerView. This method is very similar to getView method of ListView’s adapter. Now RecyclerView Adapter class is finished and final code is given below:

 

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

    private List<String> list ;
    public Context context;
    ViewHolder viewHolder;

    public Adapter(List<String> list, Context context) {

        this.list = list;
        this.context = context;
    }

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

     public void onBindViewHolder(final ViewHolder viewHolder, final int position ) {

        viewHolder.textView.setText(list.get(position));
        Picasso.with(context).load(R.drawable.image)
                             .into(viewHolder.imageView);
        viewHolder.textView.setOnClickListener(new 
           View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(),
                        "OnClick :" + list.get(position),
                        Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                 int viewType) {
        //Inflate the layout, initialize the View Holder
        View itemLayoutView = LayoutInflater.from(parent.getContext())
             .inflate(R.layout.item_list, null);

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

    // initializes textview and imageview to be used by RecyclerView.
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public ImageView imageView;

        public ViewHolder(View view) {
            super(view);

            textView = (TextView) view.findViewById(R.id.text);
            imageView = (ImageView) view.findViewById(R.id.image);
        }
    }
}

 

Make Animation while scrolling

If we want to make the animation while scrolling the recyclerview then create a up_from_bottom.xml file in the /value/anim directory

 

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="@android:anim/decelerate_interpolator">
<translate
    android:fromXDelta="30%" android:toXDelta="0%"
    android:fromYDelta="70%" android:toYDelta="0%"
    android:duration="400" />
</set>

Now, final Adapter class with animation is given below:

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

    private List<String> list ;
    public Context context;
    ViewHolder viewHolder;
    int lastPosition = -1;

    public Adapter(List<String> list, Context context) {

        this.list = list;
        this.context = context;
    }

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

     public void onBindViewHolder(final ViewHolder viewHolder, 
               final int position ) {

        viewHolder.textView.setText(list.get(position));
        Picasso.with(context).load(R.drawable.image)
                             .into(viewHolder.imageView);
        viewHolder.textView.setOnClickListener(new 
            View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(),
                        "OnClick :" + list.get(position),
                        Toast.LENGTH_SHORT).show();

            }
        });

        if(position >lastPosition) {

            Animation animation = AnimationUtils.loadAnimation(context, 
                                  R.anim.up_from_bottom);
            viewHolder.itemView.startAnimation(animation);
            lastPosition = position;
        }
    }

    @Override
    public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                 int viewType) {
        //Inflate the layout, initialize the View Holder
        View itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_list, null);

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

    // initializes textview and imageview to be used by RecyclerView.
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public ImageView imageView;

        public ViewHolder(View view) {
            super(view);

            textView = (TextView) view.findViewById(R.id.text);
            imageView = (ImageView) view.findViewById(R.id.image);
        }
    }
}

 

Set the Adapter

Now, call the adapter class and set the adapter by using setAdapter() method in the MainActivity.java file and here is your final MainActivity.java file


public class MainActivity extends AppCompatActivity {
    private List<String> list = new ArrayList<String>();
    Adapter mAdapter;

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

      RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.list);
      mRecyclerView.setHasFixedSize(true);
      mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
      arrayList();
      mAdapter = new Adapter(list,this);
      mRecyclerView.setAdapter(mAdapter);

    }

    public void arrayList(){
        for (int i = 0; i< 20; i++){
            list.add("This is row of number "+ i);
        }
    }
}

 
 

   


The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com