Reputation: 14239
I have a ViewHolder than contains, among other widgets, a SeekBar. The SeekBar has a Listener, which is added during the onCreateViewHolder
call.
Since the onBindViewHolder
method is used to configure the Views held by the ViewHolder, how can that Listener then act upon the new dataset represented by the ViewHolder's Views?
Is it OK to add a member variable of type Object to the ViewHolder, which contains a reference to the dataset, so that the Listener can then take this object and modify a variable in the dataset during SeekBar-changes? Or is this an Anti-Pattern?
The dataset object referenced by that member variable would then get swapped out on every onBindViewHolder
in order to "point" to the currently represented dataset.
Upvotes: 0
Views: 226
Reputation: 6561
If u r using a RecyclerView.ViewHolder
then u do understand that usual ViewHolder pattern's getView()
method is replaced here by 2 methods: onCreateViewHolder()
and onBindViewHolder()
. Method onCreateViewHolder()
stands for creating VH or getting it from tag and onBindViewHolder()
stands for filling VH's views with corresponding data. Understanding this the only place you shoud set the listener is onBindViewHolder()
method.
If your question is about creating a Listener
every time the onBindViewHolder()
fires - its not a good idea. You better create one instance of a listener as (adapter) class field and use it. Usually I'm setting something to a target View
's tag and this "something" is an object I need inside a listener.
private final View.OnClickListener onCancelClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
final SwipeLayout swipeLayout = (SwipeLayout) v.getParent().getParent();
swipeLayout.close();
}
};
and iside of a getView()
or onBindViewHolder()
:
viewHolder.btnSwipeMenuCancel.setTag(swipeLayout);
viewHolder.btnSwipeMenuCancel.setOnClickListener(onCancelClick);
using a tag:
viewHolder.btnSwipeMenuReply.setTag(message);
viewHolder.btnSwipeMenuReply.setOnClickListener(onReplyToAuthorClick);
private final View.OnClickListener onReplyToAuthorClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
final Message message = (Message) v.getTag();
activity.replyToMessageAuthor(message);
}
};
Upvotes: 1