Search code examples
androidandroid-recyclerviewopen-closed-principle

Proper Way to Handle Item Click Recycler View


I have 5 row to display in RecyclerView. When user clicks to one of the items, another activity opens. Each item has starts different activity. I handled the click event like below.

switch (getAdapterPosition()) {
                case 1:
                    ActivityUtil.startActivity(itemView.getContext(), BlablaActivity.class);
                    break;
                //other cases
}

It works correctly. But what if a new item is added to the list in the future? For every single item, I have to add a new case to the switch-case. This is not a proper solution according to Open Closed Principle. How should I handle it? Any suggestions would be great...


Solution

  • Ideally, you would add a Class<? extends Activity> field to the class that represents your RecyclerView items. Then you could simply access this field in your click listener (this code would be inside onCreateViewHolder()):

    holder.itemView.setOnClickListener(v -> {
        int position = holder.getAdapterPosition();
    
        if (position != RecyclerView.NO_POSITION) {
            Class<? extends Activity> activityClass = items.get(position).getActivityClass();
            ActivityUtil.startActivity(v.getContext(), activityClass);
        }
    });
    

    This way, each item is responsible for knowing where to go when it is clicked. You can add new items to your list without ever having to touch the adapter code.