Created
May 6, 2019 10:13
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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