It can be handled easily if you're strictly making the RecyclerView adapter working as a view only, i.e only showing the data with the view. All the logic decision responsibility should be delegate back to the parent activity or fragment. This can be achieved by using a Callback/Listener.
Whenever there is a click event in the RecyclerView item, tell the parent activity or fragment to handle it.
You need to change your adapter to something like this:
public class YourAdapter extends RecyclerView.Adapter<YourAdapter.ViewHolder> {
// Local variable for listener
private OnItemClickListener listener;
// Listener interface
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
// set the listener on parent activity or fragment
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
....
public ViewHolder(final View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) return;
// tell the parent to handle the item.
listener.onItemClick(itemView, position);
}
});
}
}
}
Then you can use the following to handle the click:
// assuming adapter is your adapter
adapter.setOnItemClickListener(new ContactsAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
handleItemClickByPosition(position);
}
});
...
private void handleItemClickByPosition(int position) {
switch (getAdapterPosition()) {
case 1:
ActivityUtil.startActivity(itemView.getContext(), BlablaActivity.class);
break;
//other cases
}
}
Hence you don't need to change the Adapter whenever there is new item in your Adapter.