Skip to content

Instantly share code, notes, and snippets.

@karntrehan
Last active April 23, 2019 06:30
Show Gist options
  • Save karntrehan/7ba24db9623072a3fc1e628e40fa157b to your computer and use it in GitHub Desktop.
Save karntrehan/7ba24db9623072a3fc1e628e40fa157b to your computer and use it in GitHub Desktop.
Java ListAdapter template for RecyclerView in Android
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
#parse("File Header.java")
public class ${NAME}
extends ListAdapter<${Model_Class}, ${NAME}.${ViewHolder_Class}> {
private Interaction interaction;
protected ${NAME}(Interaction interaction) {
super(new ${Model_Class}DC());
this.interaction = interaction;
}
@NonNull @Override public ${ViewHolder_Class} onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ${ViewHolder_Class}(
LayoutInflater.from(parent.getContext()).inflate(R.layout.${Item_Layout_ID}, parent, false),
interaction);
}
@Override public void onBindViewHolder(@NonNull ${ViewHolder_Class} holder, int position) {
holder.bind(getItem(position));
}
void swapData(List<${Model_Class}> data) {
submitList(data);
}
public class ${ViewHolder_Class} extends RecyclerView.ViewHolder implements View.OnClickListener {
private final Interaction interaction;
${ViewHolder_Class}(View inflate, Interaction interaction) {
super(inflate);
this.interaction = interaction;
itemView.setOnClickListener(this);
}
@Override public void onClick(View v) {
if (adapterPosition == RecyclerView.NO_POSITION) return;
${Model_Class} clicked = getItem(getAdapterPosition());
switch (v.getId()) {
//TODO handle clicks
default:
}
}
public void bind(${Model_Class} item) {
//TODO use itemView and set data
}
}
interface Interaction {
}
private static class ${Model_Class}DC extends DiffUtil.ItemCallback<${Model_Class}> {
@Override public boolean areItemsTheSame(@NonNull ${Model_Class} oldItem,
@NonNull ${Model_Class} newItem) {
//TODO "not implemented"
return false;
}
@Override public boolean areContentsTheSame(@NonNull ${Model_Class} oldItem,
@NonNull ${Model_Class} newItem) {
//TODO "not implemented"
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment