单击按钮删除recyclerview中的所有内容

时间:2018-10-03 01:09:16

标签: android android-recyclerview

我在我的应用程序中添加了一个溢出菜单,因此当用户按下菜单中的“删除”项目之一时,他们添加到回收站视图中的所有卡片视图都将被删除。

我读到我可以去做类似的事情

productList.clear();

因此我将其插入到溢出菜单代码中,但是当我按下按钮时,什么也没发生。

create.java(主要活动)

public class create extends AppCompatActivity {



    //a list to store all the products
    List<Product> productList;

    //the recyclerview
    RecyclerView recyclerView;


    Product mProduct;
    private Map<String, String> numberItemValues = new HashMap<>();
    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();


   // RelativeLayout relativeLayout;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);
        findViewById(R.id.relativeLayout).requestFocus();







        findViewById(R.id.relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) view.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        });






        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
         CSVFile csvFile = new CSVFile(inputStream);

       final List<String>  mSpinnerItems = csvFile.read();


        //getting the recyclerview from xml
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //initializing the productlist
        productList = new ArrayList<>();
        productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));




        final ProductAdapter  adapter = new ProductAdapter(this, productList, numberItemValues);


        //TODO FAB BUTTON
        FloatingActionButton floatingActionButton =
             findViewById(R.id.fab);


        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productList.add(mProduct);
                if(adapter != null)
                    adapter.notifyDataSetChanged();


                //Handle the empty adapter here

            }
        });









        //setting adapter to recyclerview
        recyclerView.setAdapter(adapter);









    }




    //TODO OVERFLOW MENU
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_delete) {



            ((ProductAdapter) recyclerView.getAdapter()).reset();



            return true;
        }





        return super.onOptionsItemSelected(item);
    }








    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");
                    //TODO I edited this part so that you'd add the values in our new hash map variable

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }



}

productadapter.java

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();

    private Map<String, String> numberItemValues = new HashMap<>();





   // private SearchableSpinner spinner;

    //we are storing all the products in a list
    private List<Product> productList;

    private Activity create;


    //TODO CODE FOR CSV FILE


    /*InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
    CSVFile csvFile = new CSVFile(inputStream);
    final List<String>  mSpinnerItems = csvFile.read();*/


    InputStream inputStream = null;
    List<String>  mSpinnerItems = null;
    CSVFile csvFile = null;


    //TODO END OF CODE FOR CSV FILE

    public ProductAdapter(Activity activity) {
        create = activity;

    }


    //getting the context and product list with constructor
    /*public ProductAdapter(Activity activity, List<Product> productList) {
        // this.mCtx = mCtx;

       *//* inputStream = create.getResources().openRawResource(R.raw.shopitems);
        csvFile = new CSVFile(inputStream);
        mSpinnerItems = csvFile.read();*//*

        create = activity;
        this.productList = productList;
    }*/


    public ProductAdapter(Activity activity, List<Product> productList, Map<String, String> numberList) {
        numberItemValues = numberList;
        create = activity;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflating and returning our view holder
        LayoutInflater inflater = LayoutInflater.from(create);
        View view = inflater.inflate(R.layout.layout_products, null);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ProductViewHolder holder, final int position) {


        // //getting the product of the specified position




        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
                Product.getSpinnerItemsList());
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        holder.spinner.setAdapter(spinnerArrayAdapter);

        holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
                mSpinnerSelectedItem.put(position, mPosition);


                TextView mTextView = view.findViewById(R.id.mSpinnerText);


                //TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW
                /*String currentItem = mSpinnerItems.get(position);
                String aisleNumber = numberItemValues.get(currentItem);
                holder.textView5.setText(aisleNumber);

*/




                //String currentItem = holder.spinner.getSelectedItem().toString();
                String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();

                Set<String> set = numberItemValues.keySet(); for(String key : set) {String value = numberItemValues.get(key); Log.e("DATA ", "key = " + key + " value = " + value); }





                //String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();
                String aisleNumber = numberItemValues.get(currentItem);
                holder.textView5.setText(aisleNumber);

                Log.e("SELECTION TEST", " Selected map item = " + aisleNumber );


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //binding the data with the viewholder views
        if (mSpinnerSelectedItem.containsKey(position)) {
            holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
        }


        holder.getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);


                // set title
                alertDialogBuilder.setTitle("Delete Item");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Are you sure you want to delete this item?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity


                                holder.checkBox.setChecked(false);
                                holder.spinner.setSelection(0);



                                productList.remove(holder.getAdapterPosition());
                                notifyItemRemoved(holder.getAdapterPosition());

                                Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();


                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });





    }


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

    public void reset() {
        productList.clear();
        notifyDatasetChanged();
    }




    class ProductViewHolder extends RecyclerView.ViewHolder {

        SearchableSpinner spinner;
        EditText editText;
        TextView textView5;
        CheckBox checkBox;
        LinearLayout linearLayout;
        View rootView;


        public ProductViewHolder(View itemView) {
            super(itemView);

            spinner = itemView.findViewById(R.id.spinner);
            editText = itemView.findViewById(R.id.editText);
            textView5 = itemView.findViewById(R.id.textView5);
            checkBox = itemView.findViewById(R.id.checkBox);
            rootView = itemView.findViewById(R.id.linearLayout);


            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // makes the set disappear when checkbox is ticked.
                    if(isChecked){

                        checkBox.setChecked(false);
                        spinner.setSelection(0);

                        productList.remove(getAdapterPosition());
                        notifyItemRemoved(getAdapterPosition());



                        Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
                    }

                }
            });



        }

        public View getView() {
            return rootView;
        }

    }






    //TODO CODE FOR CSV FILE
    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }


}

1 个答案:

答案 0 :(得分:3)

是的,您应该清除列表并致电adapter.notifyDataSetChanged()

upd

将此添加到适配器类中

 public void reset() { 
   productList.clear(); 
   notifyDataSetChanged(); 
 }

如果您的适配器变量未声明为类可见变量,则可以按以下方式调用此函数

((YourAdapterClassName) yourRecyclerView.getAdapter()).reset()

在您的情况下,它应该看起来像

floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ((ProductAdapter) recyclerView.getAdapter()).reset();

            //Handle the empty adapter here
        }
    });

适配器应包含我之前编写的函数(无效重置)

如果您想向您的RecyclerView中添加新产品 您必须创建下一个功能

public void addNewProduct(Product product){
   productList.add(product);
   notifyDataSetChanged()
}

并调用它与重置功能相同

您的简化班>>

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {


//we are storing all the products in a list
private List<Object> productList;

public ProductAdapter(Activity activity) {

}


public ProductAdapter(Activity activity, List<Object> productList, Map<String, String> numberList) {
    this.productList = productList;
}

@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //inflating and returning our view holder
    View view = new View(parent.getContext());
    return new ProductViewHolder(view);
}

@Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {


}

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


public void reset() {
    productList.clear();
    notifyDataSetChanged();
}

public void addNewProduct(Object product){
    productList.add(product);
    notifyDataSetChanged();
}

  class ProductViewHolder extends RecyclerView.ViewHolder {


    View rootView;


    public ProductViewHolder(View itemView) {
        super(itemView);


    }

    public View getView() {
        return rootView;
    }
  }
}