DEV Community

Rifqi Muttaqin
Rifqi Muttaqin

Posted on • Updated on

Learn to make list using RecyclerView

Definition

Firstly before we use that component, we must know what is RecyclerView? , and why we need that? And what the purpose of implementing this component to our app. What is RecyclerView? As references from Android documentation, RecyclerView is a similar way with ListView but with extra features, a good performance approach to displaying the list, and more benefits for displaying a large amount of data. Why we must use RecyclerView instead using ListView?, honestly is depending on yourself, some cases in our app just need ListView because the data for the list to display on the app are small, just bunch of text from the list, and implementing are simple that way, but RecyclerView more way modern and flexible, and for implementation, we need an understanding concept of RecyclerView. Here the diagram :

Dataset

All type of data we can show to the RecyclerView like :

  • Text
  • Picture
  • Icon

The data can become from anywhere, like :

  • Local database
  • Direct data with programmatically way
  • response request from API

Adapter

The Adapter has a purpose to helping interface with have no compatible for work correctly. In the RecyclerView the Adapter is ‘bridge’ for data and interface. An adapter is a carrier between the data and interface, it can receive or take the data.

RecyclerView

As the earlier article explained, RecyclerView is the component to create a list on the app, with flexible and good performance. The LayoutManager is positioning an item to the app to manage reuse items if the item not seeing by a user.

Add Dependency and Implement Component

For early guys who still learning about fundamentals, I will try to explain what I learned. Hopefully, the reader understands this implementation, otherwise, you can deeply understand using codelabs from google. For dependency you just add implementation “androidx.recyclerview:recyclerview:1.1.0 on your build.gradlew file. and for implementation into your layout, you just add using this code :

   <androidx.recyclerview.widget.RecyclerView
    android:id=“@+id/main_menu”
    android:layout_width=“wrap_content”
    android:layout_height=“wrap_content” />
Enter fullscreen mode Exit fullscreen mode

for android:layout_width and android:layout_height is depending on your case, which is your design or your parent component. After you call the main component of recyclerview, we need to create another layout for an item, for example, we create an item with icon on the left and item name in the right, the code looks like this:

      <androidx.constraintlayout.widget.ConstraintLayout
        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=“wrap_content”
        android:background=“?attr/selectableItemBackground”
        android:clickable=“true”
        android:orientation=“horizontal”
        android:paddingVertical=“15dp”
        android:focusable=“true”>

        <ImageView
            android:id=“@+id/menu_icon”
            android:layout_width=“0dp”
            android:layout_height=“wrap_content”
            android:layout_weight=“1”
            android:contentDescription=“@string/menu_desc”
            android:paddingStart=“12dp”
            android:paddingLeft=“12dp”
            android:paddingEnd=“12dp”
            android:tint=“@android:color/white”
            app:layout_constraintStart_toStartOf=“parent”
            app:layout_constraintTop_toTopOf=“parent” />

        <TextView
            android:id=“@+id/menu_item”
            android:layout_width=“wrap_content”
            android:layout_height=“wrap_content”
            android:textSize=“14sp”
            android:textStyle=“bold”
            android:textColor=“@android:color/white”
            app:layout_constraintBottom_toBottomOf=“parent”
            app:layout_constraintStart_toEndOf=“@+id/menu_icon”
            app:layout_constraintTop_toTopOf=“parent” />
    </androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

Create Adapter and Model

In the codelabs tutorial, you can directly insert data without using Model, but for good design and easy to understand and maintain in the future, we create an adapter and model class, surely in a different file. Here the example of Model I used to this article :

public class MenuModel {
    private String menuName;
    private int iconName;

    // constructor
    public MenuModel(String menuNameParam, int iconNameParam) {
        menuName = menuNameParam;
        iconName = iconNameParam;
    }

    // getter
    public String getMenuName() {
        return menuName;
    }

    // setter
    public void setMenuName(String menuNameParam) {
       this.menuName = menuNameParam;
    }

    // getter
    public int getIconName() {
        return iconName;
    }

    // setter
    public void setIconName(int iconNameParam) {
        this.iconName = iconNameParam;
    }
 }

Enter fullscreen mode Exit fullscreen mode

Wait, why you use Java ? not using Kotlin? Why ?, I think is a personal, Java programming language that has a lot of references on the internet, and if you want to use Kotlin, I recommend understanding Java in Android then try to implement it in Kotlin way. Anyway, the code adapter looks like this :

    public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {

    // storing data in adapter
    private final LinkedList<MenuModel> containMenuList; // hold data in list
    private LayoutInflater mInflater; // read layout item

    class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        // define variable
        public final TextView menuTextItemView; // for display data by TextView
        public final ImageView menuImageItemView; // for display data by ImageView
        final ModelAdapter mAdapter;

        // constructor
        public MenuViewHolder(View itemView, MenuAdapter adapter) {
            super(itemView);
            menuTextItemView = itemView.findViewById(R.id.menu_item); // menu text
            menuImageItemView = itemView.findViewById(R.id.menu_icon); // menu icon
            this.mAdapter = adapter;
            // connect onClickListener
            itemView.setOnClickListener(this);
        }
        @Override
        public void onClick(View view) {
            // when item click do something...
        }
     }

     // constructor  
     // fill constructor with inflater variable, and set LinkedList to passed data  
     public MenuAdapter(Context context, LinkedList<MenuModel> paramMenuMenuList) {  
         mInflater = LayoutInflater.from(context);  
         this.menuMenuList = paramMenuMenuList;  
     }

     // recyclerview method  
     // after fill constructor adapter, then fill recyclerview method  
     @Override  
     public MenuAdapter.MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
         View menuItemView = mInflater.inflate(R.layout.item_menu, parent, false);  // item layout
         return new MenuViewHolder(menuItemView, this);  
     }

     @Override  
     public void onBindViewHolder(MenuAdapter.MenuViewHolder holder, int position) {  
         // get the data model based on position  
         MenuModel menu = containMenuList.get(position);  
         // set item views  
         holder.menuTextItemView.setText(menu.getMenuName());
         holder.menuImageItemView.setImageResource(menu.getIconName());  
     }

     @Override
     public int getItemCount() {
         return containMenuList.size();
     }
Enter fullscreen mode Exit fullscreen mode

Implement Adapter, and Model into Main Class

To doing this, we must assume in adapter class have holder methods, and the model class has getter and setter class including constructor, after that we declare the variable in our class like this :

    // initialize list/array for recyclerview
    private final LinkedList<MenuModel> containMenuList = new LinkedList<>();
    // call member variable from adapter
    private RecyclerView mRecyclerView;
    private MenuAdapter mAdapter;
Enter fullscreen mode Exit fullscreen mode

And then implement to the main function like this, in this I’m using fragment instead Activity :

    // define root view for inflate, and call findViewById
    View rootView = inflater.inflate(R.layout.fragment_menu, container, false);

    // implement recyclerview
    // insert data into list
    containMenuList.add(new MenuModel(History, R.drawable.ic_history));
    containMenuList.add(new MenuModel(Download, R.drawable.ic_download));
    containMenuList.add(new MenuModel(My List, R.drawable.ic_list));

    // define adapter
    // Get a handle to the RecyclerView.
    mRecyclerView = rootView.findViewById(R.id.main_menu);
    // Create an adapter and supply the data to be displayed.
    mAdapter = new AccountAdapter(getActivity(), containMenuList);
    // Connect the adapter with the RecyclerView.
    mRecyclerView.setAdapter(mAdapter);
    // Give the RecyclerView a default layout manager.
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    // add divider
    mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
Enter fullscreen mode Exit fullscreen mode

Conclusion

Recyclerview is useful for displaying a list, the way we create a list is far different from others like react-native and flutter, but performance in the device is much great. Well, that’s a long journey for me, anyway, this is my first post on this website, and I'm sorry if my article has a bad language because English is not my primary language. Thank you and hopefully, you guys keep learning, and don't forget to stay healthy.

Latest comments (0)