Android RecyclerView Example

A Recyclerview is an advanced and flexible version of  a listview. RecyclerView ViewGroup is a container for larger data set of views that can be recycled and scrolled very efficiently. For using RecyclerView you need to specify an  adapter and layout manager also. A layout manager positions items views inside a recyclerview and determines when to reuse that item when it no longer visible to user.

There are some built-in Layout mangers available for recyclerview. Here we are using LinearLayoutManager for implementing a recyclerview which supports Horizontal and Vertical scrolling.

Let us see an example of recyclerview which contains list of programming languages which scroll in horizontal and vertical direction.

1.Creating New Project

  1. Create a new project in Android Studio from File -> New Project
  2. Fill the required fields like Application name and package name and click Next
  3.  Select Basic activity and click Next, and click  Finish Button.A default activity will be created as MainActivity.java with layouts activity_main.xml and content_main.xml

2. following is the code for res/layout/activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.recycler.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

3. Next you need to add Recyclerview widget to your layout content_main.xml

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.recycler.MainActivity"
    tools:showIn="@layout/activity_main"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_cards"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"/>

</RelativeLayout>

3. You need to have a layout to display recyclerview Items.For that create a file under res/layout/layout_languages_item.xml. Here i am showing only cards with one textview. you can use widgets like imageview,Button etc in this file

layout_languages_item.xml

<?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">

    <android.support.v7.widget.CardView
        android:layout_width="300dp"
        android:layout_height="300dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/card_background">

            <TextView
                android:id="@+id/tv_languages"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:textSize="24sp"
                android:textColor="@color/white"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

4. If you want to have multiple items inside a recycler item you need a model class which contains data sets .Create a class under java/your package name/LanguageModel.java .This class will contain constructor and getters and setters.

LanguageModel.java

public class LanguageModel {
    String id,language;

    public LanguageModel(String id, String language) {
        this.id = id;
        this.language = language;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}

5.Now you can create adapter class for recycler view. Create a class and name its as

LanguageListAdapter.java
public class LanguageListAdapter extends RecyclerView.Adapter<LanguageListAdapter.SingleItemRowHolder> {

    private ArrayList<LanguageModel> itemsList;
    private Activity mContext;
    int layout;

    public LanguageListAdapter(Activity context, ArrayList<LanguageModel> itemsList, int layout) {
        this.itemsList = itemsList;
        this.mContext = context;
        this.layout = layout;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(layout, null);
        SingleItemRowHolder mh = new SingleItemRowHolder(v);
        return mh;
    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        LanguageModel item = itemsList.get(i);

        holder.tv_languages.setTag(i);
        holder.tv_languages.setText(item.getLanguage());

    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tv_languages;


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

            this.tv_languages = (TextView) view.findViewById(R.id.tv_languages);


            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    int position = Integer.parseInt(tv_languages.getTag().toString());

                   Toast.makeText(v.getContext(), tv_languages.getText(), Toast.LENGTH_SHORT).show();

                }
            });


        }

    }

}

6. We need one more class DividerItemDecoration.java .What this class will do is that it will help to give divider between each items in a recyclerview. Here is the code for DividerItemDecoration.java.

DividerItemDecoration.java
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

    public DividerItemDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;


        //for vertical scrolling
      outRect.bottom = space;
      outRect.top = space;} }

7. Now you can set data from your class and add to the adapter.
Here is the full code for your MainActivity.java
MainActivity.java

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    RecyclerView rv_cards;
    LanguageListAdapter languageListAdapter;
    ArrayList<LanguageModel> languageModels;

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

        //methode for initialisation
        init();


    }

    private void init() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Languages");

        //initialisation of recycler view
        rv_cards = (RecyclerView) findViewById(R.id.rv_cards);
       // rv_cards.setHasFixedSize(true);
        rv_cards.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
        rv_cards.addItemDecoration(new DividerItemDecoration(10));


        languageModels = new ArrayList<>();

        //adding few datas into array list

            languageModels.add(new LanguageModel("1","Android"));
            languageModels.add(new LanguageModel("2","C++"));
            languageModels.add(new LanguageModel("1","C"));
            languageModels.add(new LanguageModel("1","Python"));
            languageModels.add(new LanguageModel("1","Java Script"));
            languageModels.add(new LanguageModel("1","Java"));
            languageModels.add(new LanguageModel("1","Sql"));

        //initialisation of recycler adapter
        languageListAdapter = new LanguageListAdapter(MainActivity.this, languageModels, R.layout.layout_languages_item);

        //setting adapter to recycler
        rv_cards.setAdapter(languageListAdapter);
    }

}

Output

recyclerview_vertical

Above you have seen example for vertically scrolling recyclerview. Suppose you want to change
the recycer view in veritcal direction, Then replace the line

rv_cards.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

with

rv_cards.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));

So our layout manager will manage to change the layout to horizontal scroll. Now run the code, you will get the following output

recyclerview_horizontal

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *