从列表中删除对象项

时间:2018-03-23 22:54:34

标签: java android listview android-recyclerview recycler-adapter

我想在用户 longClicked 选择 RecyclerView 项目时删除项目。 mWebsite 是一个包含两个String值的对象列表。

RecyclerViewAdapter的

setOnLongClickListener;

holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(mContext, "ITEM: "+position, Toast.LENGTH_SHORT).show();



            AlertDialog.Builder builder2 = new AlertDialog.Builder(mContext);
            builder2.setTitle("Are you sure to delete this item?");
            builder2.setMessage("'"+mWebsite.get(position).getWebUrl()+"'");


            builder2.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    mWebsite.remove(position);

                }
            });

            builder2.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });


            builder2.setCancelable(true);
            builder2.create().show();


            return true;
        }
    });

但是,我收到此错误; (第106行是; mWebsite.remove ......)

at java.util.ArrayList.get(ArrayList.java:310)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

1 个答案:

答案 0 :(得分:0)

adapter.remove(项目); adapter.notifyItemRemoved(位置);