I am confused with ViewHolder. I just started converting all my ArrayAdapters and ListView to RecyclerView with Adapters and Holders. When converting, I get stuck in the way I used to set click listeners.
Basically, in the past, I would get the position, retrieve the item at position pos and then perform the layouting of the item depending on the data in my ArrayList's item.
@SuppressLint("ClickableViewAccessibility")
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_items, null, true);
Data currentData = (Data) getItem(position);
myTextView.setText(currentData.title);
myTextView.setOnClickListener(v->actionThatDependsOnPositionAndOrData());
}
So in my ClickListener, I would have something that depends on the position, and some kind of callback that updates the ArrayList or stuff like this.
Now, it seems like I have no way to retrieve the position anymore.
@Override
public <T extends DownloadableData> void bindData(T data) {
super.bindData(data);
myTextView.setOnClickListener(v->actionThat????)
}
So how do I specify the position?
Because right now, the only way that I found in my AsyncTask in the clickListener is to call the Fragment that has the RecyclerView and do this
public void myCallback(Data data, String newTitle){
int index=allData.indexOf(data);
performModificationOfData(data); //like data.title=newTitle;
allData.set(index, data);
adapter.notifyDataSetChanged(); //not even sure this is needed..
}
Isn't there a smarter way to do it?
Please check following adapter, it will help you to understand how to set click listener on a view inside the adapter. Inside the onBindViewHolder method setOnItemClick listener. Then in the activity set that callback and you will get override method of that callback with data and position. Then do whatever you want on item click.