1 回答
TA贡献1943条经验 获得超7个赞
您的代码中有两个问题。
第一个很简单:当您单击复选框时,您会更新 的值,flag但您没有告诉RecyclerView它需要更新其内容:
checkDistance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!checkDistance.isChecked()) {
flag = false;//the flag to recycle view
}
if (checkDistance.isChecked()) {
flag = true;//the flag to recycle view
}
}
});
您可以通过在更新标志后通知适配器来解决此问题。您还可以简化布尔逻辑:
checkDistance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flag = checkDistance.isChecked();
adapter.notifyDataSetChanged();
}
});
第二个问题更复杂。问题是您使用两个不同ViewHolder的子类,具体取决于flag. 如果你想使用不同种类的 ViewHolders,你需要getItemViewType()在你的适配器中实现这个方法。
您应该确保flag 只检查inside getItemViewType(),并在其他任何地方使用此方法的结果(视图类型)。
public class DrivesRecycleViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
@Override
public int getItemViewType(int position) {
return flag ? 0 : 1;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_drive, parent, false);
if (viewType == 1) {
return new DriveViewHolder1(view);
} else {
return new DriveViewHolder2(view);
}
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Drive drive = drives.get(position);
int viewType = getItemViewType(position);
if (viewType == 1) {
DriveViewHolder1 vaultItemHolder1 = (DriveViewHolder1) holder;
vaultItemHolder1.nameTextView.setText(drive.getName());
vaultItemHolder1.phoneTextView.setText(drive.getStartAddress());//the change
} else {
DriveViewHolder2 vaultItemHolder2 = (DriveViewHolder2) holder;
vaultItemHolder2.nameTextView.setText(drive.getName());
vaultItemHolder2.phoneTextView.setText(drive.getEmail());//the change
}
}
...
}
添加回答
举报