我在RecyclerView中使用数据绑定变得疯狂。问题是它将数据绑定到多行,我无法弄清楚原因。
我尽可能简化了我的代码。当我们启动应用程序时,有200行带有标签(默认为空值)和一个按钮。当我点击一个按钮时,我的标签会改变它的值。
所以这是一个开放的活动。如您所见,没有显示标签。
让我们点击第一行的按钮
正如预期的标签出现在正确的位置。我们现在滚动。
我们可以看到标签也出现在第11位,第21位等。任何想法为什么?
我的适配器:
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
ListLearnItemBinding itemBinding = ListLearnItemBinding.inflate(layoutInflater, parent, false);
return new LearnItemViewHolder(itemBinding);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
final LearnItemViewHolder viewHolder = (LearnItemViewHolder) holder;
// init binding
if(viewHolder.getBinding().getItem2() == null){
TestBinding t = new TestBinding();
t.setRating("");
viewHolder.getBinding().setItem2(t);
}
viewHolder.getBinding().test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TestBinding item2 = new TestBinding();
item2.setRating("Label");
viewHolder.bind(item2);
}
});
}
@Override
public int getItemCount() {
return 200;
}
ViewHolder:
public class LearnItemViewHolder extends RecyclerView.ViewHolder {
public ListLearnItemBinding getBinding() {
return binding;
}
private final ListLearnItemBinding binding;
public LearnItemViewHolder(ListLearnItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(TestBinding testItem) {
binding.setItem2(testItem);
binding.executePendingBindings();
}
}
绑定模型
public class TestBinding {
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
private String rating;
}
OnCreate of my view
binding.recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
binding.recyclerView.setItemAnimator(new DefaultItemAnimator());
LearnAdapter mAdapter = new LearnAdapter(this, data);
binding.recyclerView.setAdapter(mAdapter);
布局
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(item2.rating)}" />
<Button
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
/>
答案 0 :(得分:1)
这是因为当你正在重新滚动旧视图以进行优化时。 你需要这样的东西:
private List<String> mList;
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
final LearnItemViewHolder viewHolder = (LearnItemViewHolder) holder;
TestBinding t = new TestBinding();
t.setRating(mList.get( position);
viewHolder.bind(t);
viewHolder.getBinding().test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TestBinding item2 = new TestBinding();
String label ="Label";
item2.setRating(label);
mList.set(position, label);
viewHolder.bind(item2);
}
});
}
@Override
public int getItemCount() {
return mList.size();
}