通过滑动将项目删除后,该项目将返回列表中

时间:2018-09-27 12:43:06

标签: android search filter android-recyclerview

我遇到了几天想解决的问题。 我的RecyclerView中有一个filter方法,该方法通过在edittext中编写某些内容来搜索某些项目。 RecyclerView将在一个对话框中打开,并从活动的两个edittext中填充列表,并在按下按钮后将其添加到其中。

到这里一切正常,但是我添加了一种滑动方法,该方法应该从该recyclerView删除项目,但是如果我打开它并且删除某些项目,即使我搜索某个项目,它也会以一种奇怪的方式工作。项目并删除它一切正常,但是当我搜索某个项目然后删除该项目,然后又删除另一个项目而不进行搜索时,出现问题,所以当我关闭对话框并重新打开它时,通常删除该项目而不进行搜索因为它会返回列表。

这是一个https://www.youtube.com/watch?v=Ycub3db39FQ正在恶化的视频示例,您可以看到我正在搜索5删除它,然后删除6和7,但是当我重新打开它时,6和7仍然在这里。显然,如果我再次删除它们,它们将被删除。

这是我的适配器代码和来自Activity的Dialog方法:

@TargetApi(Build.VERSION_CODES.KITKAT)
public void customAlertItems() {

    final Dialog dialog = new Dialog(this);

    dialog.setCancelable(false);

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.alert_data);

    RecyclerView recyclerView = dialog.findViewById(R.id.myRecyclerView);

    final EditText edtSearch = dialog.findViewById(R.id.edtSearch);

    ImageButton delete = dialog.findViewById(R.id.ivDelete);
    ImageButton close = dialog.findViewById(R.id.ivClose);

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    final ItemAdapter itemAdapter = new ItemAdapter(itemModel);
    recyclerView.setAdapter(itemAdapter);

    new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {

            if (direction == ItemTouchHelper.RIGHT || direction == ItemTouchHelper.LEFT) {

                model = itemAdapter.getModel();
                itemAdapter.removeItem(viewHolder.getAdapterPosition());
                edtSearch.getText().clear();


            }

        }
    }).attachToRecyclerView(recyclerView);


    edtSearch.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {

                return true;
            }
            return false;
        }
    });


    edtSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (edtSearch.getText().toString().isEmpty()) {
                if (model != null)
                    itemModel.remove(model);
            }
            itemAdapter.getFilter().filter(edtSearch.getText().toString().toLowerCase());


        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });


    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

    edtSearch.requestFocus();
    Objects.requireNonNull(dialog.getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    Objects.requireNonNull(dialog.getWindow()).setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    dialog.show();
}

这是recyclerView适配器

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ExampleViewHolder> implements Filterable {


    private ArrayList<ItemModel> variantiConstructors;
    private ArrayList<ItemModel> mFilteredList;
    private ItemModel itemModel;

    ItemAdapter(ArrayList<ItemModel> exampleList) {
        variantiConstructors = exampleList;
        mFilteredList = variantiConstructors;
    }


    @NonNull
    @Override
    public ItemAdapter.ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler, parent, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        v.setLayoutParams(lp);
        return new ItemAdapter.ExampleViewHolder(v);
    }


    @Override
    public void onBindViewHolder(@NonNull final ExampleViewHolder holder, @SuppressLint("RecyclerView") final int position) {
        ItemModel item = variantiConstructors.get(position);

        holder.desc.setText(item.getCodiceArticolo());
        holder.qta.setText(item.getQta());

        itemModel = item;

        if (position % 2 == 0) {
            holder.itemView.setBackgroundColor(Color.parseColor("#5C5C5C"));

        } else if (position % 2 == 1) {
            holder.itemView.setBackgroundColor(Color.parseColor("#9E9E9E"));
        }
    }


    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<ItemModel> results = new ArrayList<>();
                if (mFilteredList == null)
                    mFilteredList = new ArrayList<>(variantiConstructors);
                if (constraint != null && constraint.length() > 0) {
                    if (mFilteredList != null && mFilteredList.size() > 0) {
                        for (final ItemModel cd : mFilteredList) {
                            if (cd.getCodiceArticolo().toLowerCase()
                                    .contains(constraint.toString().toLowerCase()))
                                results.add(cd);
                        }
                    }
                    oReturn.values = results;
                    oReturn.count = results.size(); //newly Aded by ZA
                } else {
                    oReturn.values = mFilteredList;
                    oReturn.count = mFilteredList.size(); //newly added by ZA
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(final CharSequence constraint,
                                          FilterResults results) {
                variantiConstructors = new ArrayList<>((ArrayList<ItemModel>) results.values);
                notifyDataSetChanged();
            }
        };
    }

    @Override
    public int getItemCount() {
        return variantiConstructors.size();
    }

    public class ExampleViewHolder extends RecyclerView.ViewHolder {

        public TextView desc;
        public TextView qta;

        ExampleViewHolder(View itemView) {
            super(itemView);

            desc = itemView.findViewById(R.id.Desc);
            qta = itemView.findViewById(R.id.Qta);





        }
    }

    ItemModel getModel() {
        return itemModel;

    }

    public ArrayList<ItemModel> getList() {
        return variantiConstructors;
    }

    void removeItem(int position) {
        variantiConstructors.remove(position);
        notifyDataSetChanged();
    }
}

这是我添加项目时单击按钮的方法:

 conferma.setOnClickListener(new View.OnClickListener() {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View view) {
            if(qta.getText().length() > 4 ){
                MediaPlayer mpFound = MediaPlayer.create(InventarioActivity.this,R.raw.errorsound);
                mpFound.start();
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                Objects.requireNonNull(v).vibrate(1000);
                new GlideToast.makeToast(InventarioActivity.this, "QUANTITA' NON VALIDA", GlideToast.LENGTHLONG, GlideToast.FAILTOAST).show();
                qta.clearFocus();
            } else
                if (!code.getText().toString().equals("")) {
                    if(TextUtils.isDigitsOnly(code.getText())) {
                        if (code.getText().length() >= 1 && code.getText().length() <= 999999) {
                            if (!qta.getText().toString().equals("")) {
                                lastQta.setText(qta.getText().toString());
                                lastCode.setText(code.getText().toString());
                                itemModel.add(new ItemModel(code.getText().toString(), qta.getText().toString()));
                            } else {
                                qta.setText("1");
                                lastQta.setText(qta.getText().toString());
                                lastCode.setText(code.getText().toString());
                                itemModel.add(new ItemModel(code.getText().toString(), qta.getText().toString()));
                            }
                        } else if (code.getText().length() == 8) {

                        // check digit

                         } else if (code.getText().length() == 11) {

                        // check digit

                         } else if (code.getText().length() == 13) {

                        // check digit

                        }
                    }


                code.setText("");
                qta.setText("");
                code.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                Objects.requireNonNull(imm).showSoftInput(code, InputMethodManager.SHOW_IMPLICIT);
            }
         }
    });

1 个答案:

答案 0 :(得分:1)

尝试此操作在代码中进行以下更改,它将对您有用

  

InventarioActivity

public class InventarioActivity extends AppCompatActivity   {

    ImageButton back;
    ImageButton send;
    ImageButton itemList;
    EditText code;
    EditText qta;
    TextView lastCode;
    TextView lastQta;
    Button conferma;
    ArrayList<ItemModel> itemModel;
    RecyclerView recyclerView;
    ItemAdapter itemAdapter;
    ItemModel model;
    SharedPreferences sharedPreferences;
    String siteFTP;
    String usrFTP;
    String pswFTP;
    String path;

    String RemotesiteFTP;
    String RemoteusrFTP;
    String RemotepswFTP;
    String Remotepath;
    String qt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventario);

        back = findViewById(R.id.backButton);
        send = findViewById(R.id.sendBtn);
        itemList = findViewById(R.id.itemList);
        code = findViewById(R.id.barcodeTxt);
        qta = findViewById(R.id.qtaTxt);

        lastCode = findViewById(R.id.lastBarCode);
        lastQta = findViewById(R.id.lastQta);

        conferma = findViewById(R.id.btnConferma);

        itemModel = new ArrayList<>();

        sharedPreferences = getSharedPreferences("settings", MODE_PRIVATE);

        siteFTP = sharedPreferences.getString("siteLocal", "");
        usrFTP = sharedPreferences.getString("userLocal", "");
        pswFTP = sharedPreferences.getString("pswLocal", "");
        path = sharedPreferences.getString("localInventario", "/gpv/myfile.asc");

        RemotesiteFTP = sharedPreferences.getString("siteRemote", "");
        RemoteusrFTP = sharedPreferences.getString("userRemote", "");
        RemotepswFTP = sharedPreferences.getString("pswRemote", "");
        Remotepath = sharedPreferences.getString("remoteInventario", "");

        btnConferma();
        ItemList();
        onCodeChange();
//        sendFtp();
        qtaControll();

    }

    public void qtaControll() {
        qta.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (!hasFocus) {

                    if (qta.getText().length() > 4) {
                        if (!code.getText().toString().equals("")) {
                            lastQta.setText("1");
                            lastCode.setText(code.getText().toString());
                            itemModel.add(new ItemModel(code.getText().toString(), "1"));
                        }

                        code.setText(qta.getText());
                        qta.setText("");

                    }

                    if (!code.getText().toString().equals("")) {
                        if (TextUtils.isDigitsOnly(code.getText())) {
                            if (code.getText().length() >= 1 && code.getText().length() <= 999999) {
                                lastQta.setText(qt);
                                lastCode.setText(code.getText().toString());
                                itemModel.add(new ItemModel(code.getText().toString(), qt));
                            }
                        } else if (code.getText().length() == 8) {

                            // check digit

                        } else if (code.getText().length() == 11) {

                            // check digit

                        } else if (code.getText().length() == 13) {

                            // check digit

                        }
                    }

                }
            }
        });


        code.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    if (qta.getText().toString().equals("")) {
                        qt = "1";
                    } else {
                        qt = qta.getText().toString();
                        if (!code.getText().toString().equals("")) {
                            if (TextUtils.isDigitsOnly(code.getText())) {
                                if (code.getText().length() >= 1 && code.getText().length() <= 999999) {
                                    lastQta.setText(qt);
                                    lastCode.setText(code.getText().toString());
                                    itemModel.add(new ItemModel(code.getText().toString(), qt));
                                }
                            } else if (code.getText().length() == 8) {

                                // check digit

                            } else if (code.getText().length() == 11) {

                                // check digit

                            } else if (code.getText().length() == 13) {

                                // check digit

                            }
                        }
                    }
                }

            }
        });
    }


    public void onCodeChange() {
        code.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    qta.requestFocus();
                    return true;
                }
                return false;
            }
        });

    }

    public void ItemList() {
        itemList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customAlertItems();
            }
        });
    }


    public void btnConferma() {
        conferma.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View view) {
                if (qta.getText().length() > 4) {
//                    MediaPlayer mpFound = MediaPlayer.create(InventarioActivity.this,R.raw.errorsound);
//                    mpFound.start();
                    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    Objects.requireNonNull(v).vibrate(1000);
                    Toast.makeText(InventarioActivity.this, "QUANTITA' NON VALIDA", Toast.LENGTH_SHORT).show();
                    qta.clearFocus();
                } else if (!code.getText().toString().equals("")) {
                    if (TextUtils.isDigitsOnly(code.getText())) {
                        if (code.getText().length() >= 1 && code.getText().length() <= 999999) {
                            if (!qta.getText().toString().equals("")) {
                                lastQta.setText(qta.getText().toString());
                                lastCode.setText(code.getText().toString());
                                itemModel.add(new ItemModel(code.getText().toString(), qta.getText().toString()));
                            } else {
                                qta.setText("1");
                                lastQta.setText(qta.getText().toString());
                                lastCode.setText(code.getText().toString());
                                itemModel.add(new ItemModel(code.getText().toString(), qta.getText().toString()));
                            }
                        } else if (code.getText().length() == 8) {

                            // check digit

                        } else if (code.getText().length() == 11) {

                            // check digit

                        } else if (code.getText().length() == 13) {

                            // check digit

                        }
                    }


                    code.setText("");
                    qta.setText("");
                    code.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    Objects.requireNonNull(imm).showSoftInput(code, InputMethodManager.SHOW_IMPLICIT);
                }
            }
        });
    }

    public void customAlertItems() {

        final Dialog dialog = new Dialog(this);

        dialog.setCancelable(false);

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.alert_data);

        recyclerView = dialog.findViewById(R.id.myRecyclerView);

        final EditText edtSearch = dialog.findViewById(R.id.edtSearch);

        ImageButton delete = dialog.findViewById(R.id.ivDelete);
        ImageButton close = dialog.findViewById(R.id.ivClose);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        itemAdapter = new ItemAdapter(this, itemModel);
        recyclerView.setAdapter(itemAdapter);

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {

                if (direction == ItemTouchHelper.RIGHT || direction == ItemTouchHelper.LEFT) {
                    model = itemAdapter.getModel(viewHolder.getAdapterPosition());
                    Log.e("DATA_VALUE",model.getCodiceArticolo());
                    itemModel.remove(model);
                    itemAdapter.notifyDataSetChanged();
                    edtSearch.getText().clear();
                }

            }
        }).attachToRecyclerView(recyclerView);


        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                itemAdapter.getFilter().filter(edtSearch.getText().toString().toLowerCase());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(edtSearch.getText().toString())) {
                    itemAdapter = new ItemAdapter(InventarioActivity.this, itemModel);
                    recyclerView.setAdapter(itemAdapter);
                }

            }
        });


        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (itemAdapter.getItemCount() == 0) {
                    itemModel.clear();
                } else {
//                    itemModel = itemAdapter.getList();
                }
                dialog.dismiss();
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        edtSearch.requestFocus();
        Objects.requireNonNull(dialog.getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        Objects.requireNonNull(dialog.getWindow()).setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }


}
  

ItemAdapter

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ExampleViewHolder> implements Filterable {


    private ArrayList<ItemModel> variantiConstructors;
    private ArrayList<ItemModel> mFilteredList;
    private ItemModel itemModel;
    private Context mContext;

    ItemAdapter(Context context, ArrayList<ItemModel> exampleList) {
        variantiConstructors = exampleList;
        mFilteredList = variantiConstructors;
        mContext = context;
    }


    @NonNull
    @Override
    public ItemAdapter.ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler, parent, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        v.setLayoutParams(lp);
        return new ItemAdapter.ExampleViewHolder(v);
    }


    @Override
    public void onBindViewHolder(@NonNull final ExampleViewHolder holder, @SuppressLint("RecyclerView") final int position) {
        ItemModel item = variantiConstructors.get(position);

        holder.desc.setText(item.getCodiceArticolo());
        holder.qta.setText(item.getQta());


        if (position % 2 == 0) {
            holder.itemView.setBackgroundColor(Color.parseColor("#5C5C5C"));

        } else if (position % 2 == 1) {
            holder.itemView.setBackgroundColor(Color.parseColor("#9E9E9E"));
        }
    }


    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<ItemModel> results = new ArrayList<>();
                if (mFilteredList == null)
                    mFilteredList = new ArrayList<>(variantiConstructors);
                if (constraint != null && constraint.length() > 0) {
                    if (mFilteredList != null && mFilteredList.size() > 0) {
                        for (final ItemModel cd : mFilteredList) {
                            if (cd.getCodiceArticolo().toLowerCase()
                                    .contains(constraint.toString().toLowerCase()))
                                results.add(cd);
                        }
                    }
                    oReturn.values = results;
                    oReturn.count = results.size(); //newly Aded by ZA
                } else {
                    oReturn.values = mFilteredList;
                    oReturn.count = mFilteredList.size(); //newly added by ZA
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(final CharSequence constraint,
                                          FilterResults results) {
                variantiConstructors = new ArrayList<>((ArrayList<ItemModel>) results.values);
                notifyDataSetChanged();
            }
        };
    }

    @Override
    public int getItemCount() {
        return variantiConstructors.size();
    }

    public class ExampleViewHolder extends RecyclerView.ViewHolder {

        public TextView desc;
        public TextView qta;

        ExampleViewHolder(View itemView) {
            super(itemView);

            desc = itemView.findViewById(R.id.Desc);
            qta = itemView.findViewById(R.id.Qta);


        }
    }

    ItemModel getModel(int pos) {
        return variantiConstructors.get(pos);

    }

    public ArrayList<ItemModel> getList() {
        return variantiConstructors;
    }

}