当用户在recyclerview中按下cardview时,它将被删除

时间:2018-09-30 04:47:11

标签: android

到目前为止,我已经知道了,所以当用户按下FAB时,卡片视图会添加到recyclerview中。我现在正在尝试做到这一点,以便当用户按下卡片视图时,特定的卡片视图将从recyclerview中永久删除。

到目前为止,我有这段代码;

 mProduct.setOnClickListener(new View.OnClickListener() {


            //delete row from recyclerview
        });

但是对于setOnClickListener,它说无法解决方法

要删除cardview,我将在此链接中使用解决方案 Remove row from RecyclerView

我的其余活动代码:

public class create extends AppCompatActivity {



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

    //the recyclerview
    RecyclerView recyclerView;

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





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

        //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);

        //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

            }
        });



        mProduct.setOnClickListener(new View.OnClickListener() {


            //delete row from recyclerview
        });





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






    }



    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;
        }
    }



}

ProductAdapter.java

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

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


    //this context we will use to inflate the layout
    private Context mCtx;
    private SearchableSpinner spinner;

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





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

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

    @Override
    public void onBindViewHolder(ProductViewHolder holder, final int position) {
       // //getting the product of the specified position




        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String> (mCtx, 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);
                Toast.makeText(mCtx, "Selected Item: "+mTextView.getText().toString(), Toast.LENGTH_LONG).show();
                Log.e("***************", "Selected Item: "+mTextView.getText().toString());



            }

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

            }
        });


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






    }


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



    class ProductViewHolder extends RecyclerView.ViewHolder {

        SearchableSpinner spinner;
        EditText editText;
        TextView textView5;
        CheckBox checkBox;



        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);
        }
    }





}

Product.Java

public class Product {

    private static String editText;
    private static Boolean checkBox;
    private static String textView5;

    public static List<String> spinnerItemsList = new ArrayList<String>();

    public Product(List spinner, String editText, Boolean checkBox, String textView5) {

        this.editText = editText;
        this.spinnerItemsList = spinner;
        this.checkBox = checkBox;
        this.textView5 = textView5;
    }
    public static String getEdittext () {
        return editText;
    }

    public static boolean getCheckbox () {
        return checkBox;
    }

    public static String getTextview () {
        return textView5;
    }
    public static List<String> getSpinnerItemsList () {
        return spinnerItemsList;
    }
}

再次编辑ProductAdapter

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

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





    //this context we will use to inflate the layout
    private Context mCtx;
    private SearchableSpinner spinner;

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






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

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

    @Override
    public void onBindViewHolder(ProductViewHolder holder, final int position) {
       // //getting the product of the specified position


        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String> (mCtx, 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);
                Toast.makeText(mCtx, "Selected Item: "+mTextView.getText().toString(), Toast.LENGTH_LONG).show();
                Log.e("***************", "Selected Item: "+mTextView.getText().toString());



            }

            @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() {
            productList.remove(position);
            notifyDataSetChanged(position); });


    }







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





    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);

        }

        public View getView() {
            return rootView;
        }

    }





}

1 个答案:

答案 0 :(得分:1)

实现此目的的最简单方法是在bindviewholder方法中将侦听器添加到您的viewholder中。

public void onBindViewHolder(ViewHolder holder, final int position) {
    //Set the listener on the view of the holder
    holder.getView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mProductList.remove(position);
            notifyItemRemoved(position);  
        }
    }
}

您需要更新ViewHolder以返回可以在其上设置侦听器的CardView。

根据评论进行编辑

我使用的 getView 方法仅仅是返回您的viewholder对象的根视图。只需为根视图提供一个ID,然后在您的视图持有者中声明此方法即可。

class ProductViewHolder extends RecyclerView.ViewHolder {

    SearchableSpinner spinner;
    EditText editText;
    TextView textView5;
    CheckBox checkBox;

    //Add the base view here
    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);
        //Update the id here based on your value
        rootView = itemView.findViewById(R.id.your_view_id);
    }

    public View getView() {
        return rootView;
    }
}    

如果 notifyItemRemoved 出现错误,只需使用 notifyDataSetChanged()方法。