我见过的每一篇教程都对具有包含项目属性和isSelected
变量的类进行操作。创建项目列表时,它将存储其他变量并在onClick上对其进行更改。如何在使用Room
数据库的回收者视图中进行设置?我要实现的是长按一下,即可选择多个项目。
ItemRecyclerAdapter
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ViewHolder> {
interface ActionCallback {
void onClickListener(Item item);
void onLongClickListener(Item item);
}
private Context context;
private List<Item> itemList;
private ActionCallback mActionCallbacks;
ItemRecyclerAdapter(Context context, List<Item> itemList) {
this.context = context;
this.itemList = itemList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_list, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bindData(position);
}
@Override
public int getItemCount() {
return itemList.size();
}
void updateData(List<Item> items) {
this.itemList = items;
notifyDataSetChanged();
}
//View Holder
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private TextView mNameTextView;
private TextView mScrapCostTextView;
private ImageView mImage;
ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mScrapCostTextView= itemView.findViewById(R.id.scrap_text_view);
mNameTextView = itemView.findViewById(R.id.item_name_text_view);
mImage = itemView.findViewById(R.id.image);
}
void bindData(int position) {
Item item = itemList.get(position);
mNameTextView.setText(item.getItemName());
String scrapCost = String.valueOf(item.getScrapCost())+ " scrap";
mScrapCostTextView.setText(scrapCost);
mImage.setImageResource(item.getDrawablePath());
}
@Override
public boolean onLongClick(View v) {
if (mActionCallbacks != null) {
mActionCallbacks.onLongClickListener(itemList.get(getAdapterPosition()));
}
return true;
}
@Override
public void onClick(View view) {
if (mActionCallbacks != null) {
mActionCallbacks.onClickListener(itemList.get(getAdapterPosition()));
}
}
}
void addActionCallback(ActionCallback actionCallbacks) {
mActionCallbacks = actionCallbacks;
}