I'm trying to use a recycler view and handle on click event. I've read various methods of handling onClick event on a recycler view item like :
So my first question is which option is better? I'm currently using the first method and if defining the click listener in the view holder class itself is the way to go, then how do I use the context from the adapter as the view holder class is static.
Basically, I want to have a static view holder and on click event, open a new Activity for which I need the context.
UPDATE : Adding adapter and ViewHolder code.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context mContext;
private List<Job> jobs;
public MyAdapter(Context context, List<Job> jobs) {
mContext = context;
this.jobs = jobs;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_item, viewGroup, false);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MyActivity.class);
mContext.startActivity(intent);
}
});
return new ViewHolder(itemLayoutView);
}
@Override
public void onBindViewHolder(WorkExperienceAdapter.ViewHolder viewHolder, int i) {
//bindViewHolder code
}
}
@Override
public int getItemCount() {
return jobs.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@InjectView(R.id.current)
TextView mCurrent;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.inject(this, itemView);
}
}
}
In the view holder constructor we get the object of View class. You can use that object to get the context like:
class Holder extends RecyclerView.ViewHolder {
public Holder(View itemView) {
super(itemView);
Context context = itemView.getContext();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With