java-从RecyclerView删除对象
作者:互联网
使用ListView时,我可以通过编写this.adapter.delete(mYeets.get(position))轻松地从适配器中删除项目.使用RecyclerView,是否有等效功能?还是通知适配器我现在要做的全部更改?
private void deleteComment(int position) {
String currentUserObjectId = ParseUser.getCurrentUser().getObjectId();
ParseQuery<ParseObject> query = new ParseQuery<>("Yeet");
query.whereEqualTo(ParseConstants.KEY_OBJECT_ID, mYeets.get(position).getObjectId());
query.whereContains(ParseConstants.KEY_SENDER_ID, currentUserObjectId);
query.findInBackground((yeet, e) -> {
if (e == null) {
for (ParseObject yeetObject : yeet) {
if (yeetObject.getParseObject(ParseConstants.KEY_SENDER_AUTHOR_POINTER).getObjectId().equals((ParseUser.getCurrentUser().getObjectId()))) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle("Delete");
dialogBuilder.setMessage("Do you want to delete this Yeet?");
dialogBuilder.setPositiveButton("Yes", (dialog, which) -> {
// Iterate over all messages and delete them
for (ParseObject delete : yeet) {
delete.deleteInBackground();
//this.adapter.delete(mYeets.get(position));
this.adapter.notifyDataSetChanged();
Toast.makeText(mContext, "Yeet deleted", Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("No", (dialog, which) -> {
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
}
} else {
Log.e("Error", e.getMessage());
}
});
}
解决方法:
最好从RecyclerView.Adapter使用的数据结构(列表)中删除该项目,然后调用其notifyItemRemoved(),这是最好的方法.
先前建议的notifyDataSetChanged()不必要地使列表中的每个项目无效,而不仅仅是使位于已删除项目之后的那些无效.
标签:recycler-adapter,android-recyclerview,java,android 来源: https://codeday.me/bug/20191026/1938339.html