我已经为recyclerView创建了一个Adapter和ViewHolder。我在Viewholder中绑定了itemView的imageButton。并在onBindViewHolder中设置了一个onClickListener。
一切都如预期的那样工作,但问题是现在当我向下滚动列表时,所选项目的imageButton的选定状态发生了变化,列表底部的一些项目已经出现了选中。
下面是一些代码
public class ListViewHolder extends RecyclerView.ViewHolder {
TextView textViewUserName;
ImageButton imageButtonCheckMark;
public ListViewHolder(View itemView) {
super(itemView);
textViewUserName = (TextView) itemView.findViewById(R.id.textView_user_name);
imageButtonCheckMark = (ImageButton) itemView.findViewById(R.id.imageButton_add_user);
}
}
适配器类public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ListViewHolder> {
private LayoutInflater inflater;
private Context context;
private List<Metadata> list;
public static boolean isUserSelected = false;
ListInterface listener;
public ListAdapter(Context context, List<Metadata> data, ListInterface listener) {
Log.d(TAG, "Passed list to adapter : " + data.size());
inflater = LayoutInflater.from(context);
this.context = context;
this.list = data;
this.listener = listener;
}
@Override
public ListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_following_people, parent, false);
return new ListViewHolder(view);
}
@Override
public void onBindViewHolder(ListViewHolder holder, int position) {
holder.textViewUserName.setText(list.get(position).name);
holder.imageButtonCheckMark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isUserSelected) {
holder.imageButtonCheckMark.setImageResource(R.drawable.checkmark_green);
isUserSelected = true;
} else {
holder.imageButtonCheckMark.setImageResource(R.drawable.checkmark_grey);
isUserSelected = false;
}
listener.onUserSelected(isUserSelected, holder.getLayoutPosition());
}
});
}
@Override
public int getItemCount() {
return list.size();
}
}
Inteface类
public interface ListInterface {
public void onUserSelected(boolean userStatus, int listPosition);
}
活动内部的接口回调监听器
// Interface callback listener implemented in the activity class
private ArrayList<Metadata> metadataList = new ArrayList<>();
ArrayList<String> selectedUserIdList = new ArrayList<>();
@Override
public void onUserSelected(boolean isUserSelected, int pos) {
if (isUserSelected) {
Log.d(TAG, "Selected user Id: " + metadataList.get(pos).userID);
followersSelectedIdList.add(metadataList.get(pos).userID);
} else {
Log.d(TAG, "Removed user Id: " + metadataList.get(pos).userID);
followersSelectedIdList.remove(metadataList.get(pos).userID);
}
}
在你的模型类中添加一个属性来保存按钮是否被选中的状态,在onBindViewHolder()中编写代码来像这样管理按钮视图,
if(yourModel.getIsSelected()){
// positive view
} else {
//negative view
}
您看到这种行为是因为视图在滚动时被重用(回收)。您需要保存列表中所有按钮的状态,并在onBindViewHolder()中设置每个按钮的状态,因为它变得可见。