Main navigation

Listing Items using RecyclerView

adsense

Pre-requisites

  1. Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. .

Creating a New Project

We would be listing Scientists so create a new Scientist.java class which will have all the field as well getter,setter methods required for a Scientist. Add the following code to the class

Scientist.java

package com.androidtutorialpoint.listviewtutorial;
public class Scientist {
    private String mName;
    private String mBirthYear;
    private String mDeathYear;
    private int mImageId;
    public String getName() {
        return mName;
    }
    public void setName(String mName) {
        this.mName = mName;
    }
    public String getBirthYear() {
        return mBirthYear;
    }
    public void setBirthYear(String mBirthYear) {
        this.mBirthYear = mBirthYear;
    }
    public String getDeathYear() {
        return mDeathYear;
    }
    public void setDeathYear(String mDeathYear) {
        this.mDeathYear = mDeathYear;
    }
    public int getImageId() {
        return mImageId;
    }
    public void setImageId(int mImageId) {
        this.mImageId = mImageId;
    }
}

Adding Support Library for RecyclerView

  1. Navigate to your project structure window by clicking on File -> Project Structure .
  2. Select the app module on the left, then the Dependencies tab.
  3. recyclerview1

  4. Use the + button and choose Library dependency to add a dependency.
  5. Find and select the recyclerview-v7 library and click OK to add the library as a dependency, as shown in Figure

recyclerview2

Now Gradle will sync your project and add the dependencies.

Add a RecyclerView

  1. Create a layout file by Right-clicking on the res/layout directory and selectingNew → Layout resource file . Name the file fragment_listscientists.xml and click OK to create the file.Open the file add the following code.
  2. fragment_listscientists.xml

    <android.support.v7.widget.RecyclerView xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/scientist_recycler_view" android:scrollbars="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    
    
  3. Each item in the list will consist of an imageView to show Scientists Image , A textView to show his/her name and another textView to show the year of birth and death.

    To achieve it create a layout file category_list_item_1.xml and paste the following code.

  4. category_list_item_1.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp">
        <ImageView android:id="@+id/imageView" android:layout_width="80dp" android:layout_height="80dp" />
        <TextView android:paddingTop="10dp" android:paddingLeft="10dp" android:id="@+id/textview_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="25dp" android:textStyle="bold" android:layout_toRightOf="@id/imageView" android:layout_alignParentRight="@id/imageView"/>
        <TextView android:id="@+id/textview_birth_death" android:paddingLeft="10dp" android:textSize="18dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/imageView" android:layout_alignParentRight="@id/imageView" android:layout_below="@id/textview_name"/>
    </RelativeLayout>
    
    

Adding The Functionality

  1. Create a new fragment, name it ListScientistsFragment.java and add the following code.

    Let’s use arrays to store the name , birth year, death year and ImageId for each scientists. I have already added the photos of scientists to the drawable folder. You can download the code by clicking on the Download Now Button provided at the top.

  2.  
    
        private String[] scientistNames = {"Marie Curie","Thomas Edison","Albert Einstein","Michael Faraday","Galileo Galilei",
                "Stephen Hawking","Johannes Kepler","Issac Newton","Nikola Tesla"};
        private String[] birthYear = {"1867","1847","1879","1791","1564","1942","1571","1643","1856"};
        private String[] deathYear = {"1934","1931","1955","1867","1642","Present","1630","1727","1943"};
        private int[] image = {R.drawable.curie,R.drawable.edison,R.drawable.einstein,R.drawable.faraday,R.drawable.galileo,R.drawable.hawking,R.drawable.kepler,R.drawable.newton,R.drawable.tesla};
    
    
    
  3. In the onCreate method create a Scientist ArrayList which will be passed to the Adapter later.
  4.     @Override
        public void onCreate(Bundle savedInstanceState) {
            mScientists = new ArrayList<>();
            for(int i =0;i<scientistNames.length;i++){
                Scientist s = new Scientist();
                s.setName(scientistNames[i]);
                s.setBirthYear(birthYear[i]);
                s.setDeathYear(deathYear[i]);
                s.setImageId(image[i]);
                mScientists.add(s);
            }
            super.onCreate(savedInstanceState);
        }
    
    
    
  5. A view Holder is required to hold on to the views, so add the following code.
  6. private class ScientistHolder extends RecyclerView.ViewHolder{
        private Scientist mScientist;
        public ImageView mImageView;
        public TextView mNameTextView;
        public TextView mBirthDeathTextView;
        public ScientistHolder(View itemView){
            super(itemView);
            mImageView = (ImageView) itemView.findViewById(R.id.imageView);
            mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
            mBirthDeathTextView = (TextView) 			  	       			itemView.findViewById(R.id.textview_birth_death);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),
                            mScientist.getName() + " clicked!", Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
        public void bindData(Scientist s){
            mScientist = s;
            mImageView.setImageResource(s.getImageId());
            mNameTextView.setText(s.getName());
            mBirthDeathTextView.setText(s.getBirthYear()+"-"+s.getDeathYear());
        }
    }
    
    

    The above code extends the RecyclerView.ViewHolder class and references the ImageView and the TextViews for each view it will be holding.It also has a setOnClickListener() which shows a Toast for the item that was clicked.You may replace this and start an activity showing the details for the item clicked.

  7. Next, extend the RecyclerView.Adapter class, this adapter is link between the RecyclerView and the data which we want to list. It creates required ViewHolders and also the binds the ViewHolder to data from the Scientist class.

    It has three main methods:

    1. onCreateViewHolder : Inflates the layout and creates a new view Holder.
    2. onBindViewHodler : Binds the data to the view holder.
    3. getItemCount : returns the size of the data to be dispalyed.

    use the following code to create a ScientistAdapter.

  8.     private class ScientistAdapter extends RecyclerView.Adapter<ScientistHolder>{
            private ArrayList<Scientist> mScientists;
            public ScientistAdapter(ArrayList<Scientist> Scientists){
                mScientists = Scientists;
            }
            @Override
            public ScientistHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                    View view = layoutInflater.inflate(R.layout.category_list_item_1,parent,false);
                    return new ScientistHolder(view);
            }
            @Override
            public void onBindViewHolder(ScientistHolder holder, int position) {
                Scientist s = mScientists.get(position);
                holder.bindData(s);
    
            }
            @Override
            public int getItemCount() {
                return mScientists.size();
            }
        }
    }
    
  9. Additionally we have created a method updateUI() to create an Adapter Object and set the adapter to the Recycler view
  10.     private void updateUI(){
            mAdapter = new ScientistAdapter(mScientists);
            mScientistRecyclerView.setAdapter(mAdapter);
        }
    
  11. In the onCreateView() method of the ListScientistsFragment, we reference the RecyclerView we have added in the layout file. The setLayoutManager() method asks the LayoutManager to handle the positioning of the list items and scrolling behaviour.
  12. @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_listscientists, container, false);
            mScientistRecyclerView = (RecyclerView) view
                    .findViewById(R.id.scientist_recycler_view);
    	        mScientistRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
            mScientistRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            updateUI();
            return view;
        }
    
    
  13. The addItemDecoration() is used here to add a separator line for each item. Create a java file SimpleDividerItemDecoration and add the following code
  14. SimpleDividerItemDecoration .java

    package com.androidtutorialpoint.listviewtutorial;
        import android.content.res.Resources;
            import android.graphics.Canvas;
            import android.graphics.drawable.Drawable;
            import android.support.v7.widget.RecyclerView;
            import android.view.View;
    public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration{
        private Drawable mDivider;
        public SimpleDividerItemDecoration(Resources resources) {
            mDivider = resources.getDrawable(R.drawable.divider);
        }
        public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
                RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
                int top = child.getBottom() + params.bottomMargin;
                int bottom = top + mDivider.getIntrinsicHeight();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
    
  15. Also create an xml file drawer.xml and add it to your app’s drawable folder.
  16. divider.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="rectangle">
        <size android:width="1dp" android:height="1dp" />
        <solid android:color="#999999" />
    </shape>
    

    Here is the completed ListScientistsFragment file.

    ListScientistsFragment.java

    package com.androidtutorialpoint.listviewtutorial;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.ListFragment;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.transition.Scene;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.lang.reflect.Array;
    import java.util.ArrayList;
    /**
     * Created by anonymous on 10/30/15.
     */
    public class ListScientistsFragment extends Fragment {
        private final String TAG = "ListScientistsFragment";
        private String[] scientistNames = {"Marie Curie","Thomas Edison","Albert Einstein","Michael Faraday","Galileo Galilei",
                "Stephen Hawking","Johannes Kepler","Issac Newton","Nikola Tesla"};
        private String[] birthYear = {"1867","1847","1879","1791","1564","1942","1571","1643","1856"};
        private String[] deathYear = {"1934","1931","1955","1867","1642","Present","1630","1727","1943"};
        private int[] image = {R.drawable.curie,R.drawable.edison,R.drawable.einstein,R.drawable.faraday,R.drawable.galileo,R.drawable.hawking,R.drawable.kepler,R.drawable.newton,R.drawable.tesla};
        private ArrayList<Scientist> mScientists;
        private RecyclerView mScientistRecyclerView;
        private ScientistAdapter mAdapter;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            mScientists = new ArrayList<>();
            for(int i =0;i<scientistNames.length;i++){
                Scientist s = new Scientist();
                s.setName(scientistNames[i]);
                s.setBirthYear(birthYear[i]);
                s.setDeathYear(deathYear[i]);
                s.setImageId(image[i]);
                mScientists.add(s);
            }
            super.onCreate(savedInstanceState);
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_listscientists, container, false);
            mScientistRecyclerView = (RecyclerView) view
                    .findViewById(R.id.scientist_recycler_view);
            mScientistRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
            mScientistRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            updateUI();
            return view;
        }
        private void updateUI(){
            mAdapter = new ScientistAdapter(mScientists);
            mScientistRecyclerView.setAdapter(mAdapter);
        }
        private class ScientistHolder extends RecyclerView.ViewHolder{
            private Scientist mScientist;
            public ImageView mImageView;
            public TextView mNameTextView;
            public TextView mBirthDeathTextView;
            public ScientistHolder(View itemView){
                super(itemView);
                mImageView = (ImageView) itemView.findViewById(R.id.imageView);
                mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
                mBirthDeathTextView = (TextView) itemView.findViewById(R.id.textview_birth_death);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(),
                                mScientist.getName() + " clicked!", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }
            public void bindData(Scientist s){
                mScientist = s;
                mImageView.setImageResource(s.getImageId());
                mNameTextView.setText(s.getName());
                mBirthDeathTextView.setText(s.getBirthYear()+"-"+s.getDeathYear());
            }
        }
        private class ScientistAdapter extends RecyclerView.Adapter<ScientistHolder>{
            private ArrayList<Scientist> mScientists;
            public ScientistAdapter(ArrayList<Scientist> Scientists){
                mScientists = Scientists;
            }
            @Override
            public ScientistHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                    View view = layoutInflater.inflate(R.layout.category_list_item_1,parent,false);
                    return new ScientistHolder(view);
            }
            @Override
            public void onBindViewHolder(ScientistHolder holder, int position) {
                Scientist s = mScientists.get(position);
                holder.bindData(s);
            }
            @Override
            public int getItemCount() {
                return mScientists.size();
            }
        }
    }
    
    
  17. Next, we will be hosting ListScientistsFragment in the MainActivity. Open MainActivity.java and add the following code.

MainActivity

package com.androidtutorialpoint.listviewtutorial;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
        if (fragment == null) {
            fragment = new ListScientistsFragment();
            ;
            fm.beginTransaction()
                    .add(R.id.fragmentContainer, fragment)
                    .commit();
        }
    }
}

As shown in tutorial we have hosted the ListScientistsFragment in the MainActivity.

The layout file for MainActivity i.e. activity_main.xml consists of a FrameLayout as a fragmentContainer.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/fragmentContainer" />

Run the App and you should see a scrollable List of Scientists. Please comment in case you have any doubts or suggestions.



What’s Next

We hope this tutorial will help you getting started with RecyclerView on Android. You can use this knowledge to create beautiful apps that have a list interface. Please refer to the following tutorial to learn about CardView which is an extension of RecyclerViewAndroid CardView Tutorial. Stay tuned for more tutorials and don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

Click on the Download Now button to download the full code.

Android Tutorial Point Download Now


Reader Interactions

Comments

  1. Hey there,
    Thanks for writing this awesome tutorial for android community.

    You have explained superbly with detail list of codes.

    Thank you

  2. First of all, thanks for writing such great tutorial.

    You are doing fabulous job here.

    Keep sharing such great tutorial with us.

    Thanks

  3. I must say you have high quality posts here.
    Your page should go viral. You need initial boost only.
    How to get it? Search for: Etorofer’s strategies

Leave a Reply

Advertisment ad adsense adlogger