Monday, December 30, 2024
Google search engine
HomeLanguagesJavaAndroid | Horizontal RecyclerView with Examples

Android | Horizontal RecyclerView with Examples

RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user.

For example: if a user scrolled down to a position where the items 4 and 5 are visible; items 1, 2 and 3 would be cleared from the memory to reduce memory consumption.

In this article, we will learn how to create recycler view which can be scrolled in a horizontal direction.

Here are the detailed steps:

  1. Step 1: Add the dependency of Recycler View widget in your project
    • Latest dependency for Recycler View is:
      implementation 'com.android.support:recyclerview-v7:28.0.0'
      
    • Also add the dependency for Card View. Latest dependency for Card View is:
      implementation 'com.android.support:cardview-v7:28.0.0'
      
  2. Step 2: Setting up the activity_main.xml layout file
    The activity_main.xml layout file consists of:
    • Relative layout which contains the recycler view
    • Recycler view widget

    Here is complete code for activity_main.xml:

    activity_main.xml




    <?xml version="1.0" encoding="utf-8"?>
      
    <!--Relative Layout-->
    <RelativeLayout 
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.neveropen.horizontalrecyclerview.MainActivity"
        android:id="@+id/relativelayout">
      
        <!--Recycler View widget-->
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:scrollbars="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
      
    </RelativeLayout>

    
    
  3. Step 3: Setting up the item.xml layout file for Recycler view
    The item.xml layout file consists of the layout for an item of Recycler View. Item Layout contains a Card View with Text view in it with some text.
    Here is complete code for item.xml:

    item.xml




    <?xml version="1.0" encoding="utf-8"?>
      
    <!--Card View widget-->
    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cardview"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        card_view:contentPadding="8dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardElevation="8dp"
        card_view:cardBackgroundColor="#0F9D58"
        android:layout_margin="1dp"
        >
      
        <!--Text View over Card View-->
        <TextView
            android:id="@+id/textview"
            android:layout_gravity="center"'
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:textSize="22dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#fff"/>
      
    </android.support.v7.widget.CardView>

    
    
  4. Step 4: Setting up the code for Recycler View Adapter
    The adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are:
    • onCreateViewHolder,
    • onBindViewHolder,
    • getItemCount

    The adapter is used to set data to Recycler View from Data source.

    Here is complete code for adapter.java:

    Adapter.java




    package com.neveropen.horizontalrecyclerview;
      
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.view.LayoutInflater;
    import java.util.List;
      
    // The adapter class which
    // extends RecyclerView Adapter
    public class Adapter
        extends RecyclerView.Adapter<Adapter.MyView> {
      
        // List with String type
        private List<String> list;
      
        // View Holder class which
        // extends RecyclerView.ViewHolder
        public class MyView
            extends RecyclerView.ViewHolder {
      
            // Text View
            TextView textView;
      
            // parameterised constructor for View Holder class
            // which takes the view as a parameter
            public MyView(View view)
            {
                super(view);
      
                // initialise TextView with id
                textView = (TextView)view
                               .findViewById(R.id.textview);
            }
        }
      
        // Constructor for adapter class
        // which takes a list of String type
        public Adapter(List<String> horizontalList)
        {
            this.list = horizontalList;
        }
      
        // Override onCreateViewHolder which deals
        // with the inflation of the card layout
        // as an item for the RecyclerView.
        @Override
        public MyView onCreateViewHolder(ViewGroup parent,
                                         int viewType)
        {
      
            // Inflate item.xml using LayoutInflator
            View itemView
                = LayoutInflater
                      .from(parent.getContext())
                      .inflate(R.layout.item,
                               parent,
                               false);
      
            // return itemView
            return new MyView(itemView);
        }
      
        // Override onBindViewHolder which deals
        // with the setting of different data
        // and methods related to clicks on
        // particular items of the RecyclerView.
        @Override
        public void onBindViewHolder(final MyView holder,
                                     final int position)
        {
      
            // Set the text of each item of
            // Recycler view with the list items
            holder.textView.setText(list.get(position));
        }
      
        // Override getItemCount which Returns
        // the length of the RecyclerView.
        @Override
        public int getItemCount()
        {
            return list.size();
        }
    }

    
    
  5. Step 5. Setting up the code for MainActivity.java file for Recycler view
    The MainActivity contains RecyclerView. Set Layout Manager on Recycler view using LinearLayoutManager class.
    Here is complete code for MainActivity.java:

    MainActivity.java




    package com.neveropen.horizontalrecyclerview;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.LinearLayoutManager;
    import android.view.View;
    import android.widget.Toast;
    import java.util.ArrayList;
      
    public class MainActivity extends AppCompatActivity {
      
        // Recycler View object
        RecyclerView recyclerView;
      
        // Array list for recycler view data source
        ArrayList<String> source;
      
        // Layout Manager
        RecyclerView.LayoutManager RecyclerViewLayoutManager;
      
        // adapter class object
        Adapter adapter;
      
        // Linear Layout Manager
        LinearLayoutManager HorizontalLayout;
      
        View ChildView;
        int RecyclerViewItemPosition;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            // initialisation with id's
            recyclerView
                = (RecyclerView)findViewById(
                    R.id.recyclerview);
            RecyclerViewLayoutManager
                = new LinearLayoutManager(
                    getApplicationContext());
      
            // Set LayoutManager on Recycler View
            recyclerView.setLayoutManager(
                RecyclerViewLayoutManager);
      
            // Adding items to RecyclerView.
            AddItemsToRecyclerViewArrayList();
      
            // calling constructor of adapter
            // with source list as a parameter
            adapter = new Adapter(source);
      
            // Set Horizontal Layout Manager
            // for Recycler view
            HorizontalLayout
                = new LinearLayoutManager(
                    MainActivity.this,
                    LinearLayoutManager.HORIZONTAL,
                    false);
            recyclerView.setLayoutManager(HorizontalLayout);
      
            // Set adapter on recycler view
            recyclerView.setAdapter(adapter);
        }
      
        // Function to add items in RecyclerView.
        public void AddItemsToRecyclerViewArrayList()
        {
            // Adding items to ArrayList
            source = new ArrayList<>();
            source.add("gfg");
            source.add("is");
            source.add("best");
            source.add("site");
            source.add("for");
            source.add("interview");
            source.add("preparation");
        }
    }

    
    

Output:

RELATED ARTICLES

Most Popular

Recent Comments