从RecyclerView中删除对象

时间:2016-09-19 13:39:19

标签: java android android-recyclerview recycler-adapter

使用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());
        }
    });
}

2 个答案:

答案 0 :(得分:3)

如果您正在使用RecyclerView,只需从列表中删除该项目并调用方法notifiyDataSetChanged;

答案 1 :(得分:1)

只需从RecyclerView.Adapter使用的数据结构(List)中删除该项,然后调用其notifyItemRemoved()应该是最好的方法。

之前建议的notifyDataSetChanged()会不必要地使列表中的每个项目无效,而不仅仅是位于已删除项目之后的项目。