如果用户另有决定,我正在努力实现删除Recyclerview条目并重新添加它的功能。为此,我展示了Snackbar
撤消操作。
所以流程应该是:用户看到Cards
的列表,每个列表都显示一些值和删除按钮。如果用户按下删除按钮,则会删除该卡并显示Snackbar
。如果用户点击Snackbar
上的撤消操作,Card
应重新添加到RecyclerView
。仅当Snackbar
超时消失时,相应的条目也应从SQLite
数据库中删除。
我填充相应TextViews
的{{1}}并在Cards
中设置删除按钮的OnClickListener
。
我的课程onBindViewHolder
延伸CardApater
如下所示:
RecyclerView.Adapter<CardAdapter.CardViewHolder>
删除卡有效,但在将CardEntry重新添加到列表时,应用程序在private List<CardEntry> cards;
public CardAdapter(List<CardEntry> cards) {
this.cards = cards;
}
@Override
public int getItemCount() {
return cards.size();
}
@Override
public void onBindViewHolder(final CardViewHolder cardViewHolder, int i) {
final CardEntry card = cards.get(i);
cardViewHolder.tvDate.setText(card.date);
cardViewHolder.tvValue1.setText(card.value1);
cardViewHolder.tvValue2.setText(card.value2);
cardViewHolder.tvValue3.setText(card.value3);
cardViewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cards.remove(cardViewHolder.getAdapterPosition());
notifyDataSetChanged();
Snackbar snack = Snackbar.make(view, "Deleted", Snackbar.LENGTH_LONG);
snack.setAction("Undo", this);
snack.setActionTextColor(Color.RED);
snack.setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
switch (event) {
case DISMISS_EVENT_ACTION:
cards.add(card);
notifyDataSetChanged();
break;
case DISMISS_EVENT_TIMEOUT:
MainActivity.datasource.deleteSQLiteEntry(card.id);
break;
}
}
});
snack.show();
}
});
}
@Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.cardview, viewGroup, false);
return new CardViewHolder(itemView);
}
public static class CardViewHolder extends RecyclerView.ViewHolder {
protected TextView tvDate;
protected TextView tvValue1;
protected TextView tvValue2;
protected TextView tvValue3;
protected ImageView deleteButton;
public CardViewHolder(View v) {
super(v);
tvDate = (TextView) v.findViewById(R.id.date);
tvValue1 = (TextView) v.findViewById(R.id.value1);
tvValue2 = (TextView) v.findViewById(R.id.value2);
tvValue3 = (TextView) v.findViewById(R.id.value3);
deleteButton = (ImageView) v.findViewById(R.id.delete);
}
}
方法的ArrayIndexOutOfBoundsException: length=12; index=-1
行与cards.remove(cardViewHolder.getAdapterPosition());
崩溃。
我们非常感谢您在添加新条目时对此提出的任何建议或原因onClick
。