Skip to content

Instantly share code, notes, and snippets.

@mattiaferigutti
Created April 20, 2021 13:13
Show Gist options
  • Save mattiaferigutti/91cf129654cf25e6959fa0fadc6d2c9e to your computer and use it in GitHub Desktop.
Save mattiaferigutti/91cf129654cf25e6959fa0fadc6d2c9e to your computer and use it in GitHub Desktop.
package com.studio.mattiaferigutti.itiproject;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import com.studio.mattiaferigutti.itiproject.databinding.RowLayoutBinding;
public class UserAdapter extends ListAdapter<User, UserAdapter.ViewHolder> {
private OnItemClickListener listener;
public interface OnItemClickListener {
void onItemSelected(User user);
}
public UserAdapter(OnItemClickListener listener) {
super(new UserDiffCallback());
this.listener = listener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return ViewHolder.from(parent);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User item = getItem(position);
holder.itemView.setOnClickListener(v -> {
listener.onItemSelected(item);
});
holder.bind(item);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private final RowLayoutBinding binding;
public ViewHolder(@NonNull RowLayoutBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(User item) {
binding.setUser(item);
binding.executePendingBindings();
}
public static ViewHolder from(ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RowLayoutBinding binding = RowLayoutBinding.inflate(layoutInflater, parent, false);
return new ViewHolder(binding);
}
}
}
class UserDiffCallback extends DiffUtil.ItemCallback<User> {
@Override
public boolean areItemsTheSame(@NonNull User oldItem, @NonNull User newItem) {
return oldItem.equals(newItem);
}
@Override
public boolean areContentsTheSame(@NonNull User oldItem, @NonNull User newItem) {
return (oldItem.getFirstName().equals(newItem.getFirstName())) &&
(oldItem.getLastName().equals(newItem.getLastName())) &&
(oldItem.getEmail().equals(newItem.getEmail()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment