问题
If we have a RecyclerView
that will have views of different type we can inflate the view we need based on an item type e.g.
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
View view = null;
switch (type) {
case TYPEX:
view = LayoutInflater
.from(viewGroup.getContext())
.inflate(R.layout.typex, viewGroup, false);
return new ViewHolderX(view);
case TYPEY:
view = LayoutInflater
.from(viewGroup.getContext())
.inflate(R.layout.typey, viewGroup, false);
return new ViewHolderY(view);
}
return null;
}
So far so good. The views then are reusable in the ViewHolder
Question:
If TYPEX
view has a button that on press changes something in the view e.g. the background color, this means that when the view is recycled the color will be different for other items that the user never pressed the button for.
How can this be addressed since it would not be related to any condition of the data that the view has to display from the adapter?
回答1:
You should store your Property [background color] inside model and make decision based on that.
class Model {
...
private int backgroundColor = 0xFFFFFF;
public int getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
}
...
}
Handle click here and update background color.
@Override
public void onBindViewHolder(@NonNull final SuggestionHomeAdapter.ViewHolder holder, final int position) {
final Model model = modelItems.get(position);
holder.rootView.setBackgroundColor(model.getBackgroundColor());
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(model.getBackgroundColor() != 0xFFFF0000){
model.setBackgroundColor(0xFFFF0000);
notifyItemChanged(position);
}
}
});
}
It persists with model by position not view. So only those item affected that are click by user. Thanks
来源:https://stackoverflow.com/questions/58577949/how-to-handle-ui-changes-from-interaction-with-a-view-when-using-a-recyclerview