Skip to content

Instantly share code, notes, and snippets.

@nwagu
Created May 6, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwagu/d88bb2f30d8a2ed3f525d2edca683e48 to your computer and use it in GitHub Desktop.
Save nwagu/d88bb2f30d8a2ed3f525d2edca683e48 to your computer and use it in GitHub Desktop.
How do I set OnClick Listener inside recycler adapter when using unknown ViewDatabinding instead of ItemDatabinding?
public class ExampleListAdapter extends MyBaseAdapter {
private Context context;
private List<Example> exampleList;
public ExampleListAdapter(Context context, List<Example> exampleList) {
this.context = context;
this.exampleList = exampleList;
}
@Override
public int getItemCount() {
return exampleList.size();
}
@Override
protected Example getObjForPosition(int position) {
return exampleList.get(position);
}
@Override
protected int getLayoutIdForPosition(int position) {
return R.layout.example_view;
}
@Override
public View.OnClickListener getOnItemClickListener(int position) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do action using context, for instance ...
// context.startActivity(intent);
}
};
}
}
public abstract class MyBaseAdapter extends RecyclerView.Adapter<MyViewHolder> {
@NonNull
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(parent.getContext());
ViewDataBinding binding = DataBindingUtil.inflate(
layoutInflater, viewType, parent, false);
return new MyViewHolder(binding);
}
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Object obj = getObjForPosition(position);
holder.itemView.setOnClickListener(getOnItemClickListener(position));
holder.bind(obj);
}
@Override
public int getItemViewType(int position) {
return getLayoutIdForPosition(position);
}
protected abstract Object getObjForPosition(int position);
protected abstract int getLayoutIdForPosition(int position);
protected abstract View.OnClickListener getOnItemClickListener(int position);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment