So after 5 months of webdevelopment I needed to get back into android but I noticed some of my old code isn't working anymore. I have a RecyclerView with a adapter for the data but the onClickListener for the items doesn't respond to anything. This is what my code looks like:
public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ViewHolder> {
private List<Project> itemsData;
OnItemClickListener mItemClickListener;
public ProjectAdapter(List<Project> itemsData) {
this.itemsData = itemsData;
}
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new views
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
// create ViewHolder
ViewHolder vh = new ViewHolder(itemLayoutView);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.txtViewId.setText(String.valueOf(itemsData.get(position).getId()));
viewHolder.txtViewName.setText(itemsData.get(position).getName());
}
// inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView txtViewName, txtViewId;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewName = (TextView) itemLayoutView.findViewById(R.id.item_name);
txtViewId = (TextView) itemLayoutView.findViewById(R.id.item_id);
}
@Override
public void onClick(View v) {
System.out.println("onClick");
TextView tv = (TextView) v.findViewById(R.id.item_name);
String id = tv.getText().toString();
mItemClickListener.onItemClick(v, getAdapterPosition(), id); //OnItemClickListener mItemClickListener;
}
}
public interface OnItemClickListener {
public void onItemClick(View view, int position, String id);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
// Return the size of your itemsData (invoked by the layout manager)
@Override
public int getItemCount() {
return itemsData.size();
}
}
ProjectsActivity.java
projectAdapter.SetOnItemClickListener(new ProjectAdapter.OnItemClickListener() {
@Override
public void onItemClick(View v, int position, String id) {
System.out.println("onItemClick" + id);
ActionActivity(id);
}
});
The list gets showed, the click doesn't work, not even the log to the console. Does anybody know what I've been doing wrong? I'm using SDK v23 as the compile sdk version. My minimum SDK version is v19.
add a click after finding View like this:
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewName = (TextView) itemLayoutView.findViewById(R.id.item_name);
txtViewId = (TextView) itemLayoutView.findViewById(R.id.item_id);
// here
itemLayoutView.setOnClickListener(this);
}