选中复选框以删除RecylerView行将删除其他行

时间:2018-10-01 05:17:28

标签: android android-recyclerview android-checkbox

当用户按下FAB时,卡片视图将添加到回收站视图。每个Cardview内部都有一个复选框。我要这样做,以便当用户在特定卡片视图中打勾时,该特定卡片视图被删除。

但是我现在有问题。可以说我通过按fab分别添加1、2、3和4来添加4个cardview。当我在cardview 3中选中复选框时,cardview 4消失了。但是,cardview 3中的复选框已打勾。当我单击以取消选中cardview 3中的复选框时,cardview 3消失了。因此,从本质上讲,它删除的是错误的Cardview,而不是自己的。

以下是显示更多说明的屏幕记录:https://streamable.com/vuq5t

这是我的代码

ProductAdapter

// Call Fetch Event
self.addEventListener('fetch', e => {
  console.log('Service Worker: Fetching');
  e.respondWith(
    fetch(e.request)
      .then(res => {
        // Make copy/clone of response
        const resClone = res.clone();
        // Open cahce
        caches.open(cacheName).then(cache => {
          // Add response to cache
          cache.put(e.request, resClone);
        });
        return res;
      })
      .catch(err => caches.match(e.request).then(res => res))
  );
});

create.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
    //Remove this..Please
    // CheckBox checkBox;

    //private Context mCtx;
    private SearchableSpinner spinner;

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

    private Activity create;

    public ProductAdapter(Activity activity) {
        create = activity;
    }


    //getting the context and product list with constructor
    public ProductAdapter(Activity activity, List<Product> productList) {
        // this.mCtx = mCtx;
        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(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);
           /* Toast.makeText(create, "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() {
            @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

                                productList.remove(position);
                                notifyItemRemoved(position);

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

            }
        });


        //checkbox ticked
        //here do holder.checkbox take your view holder checkbox

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

                productList.remove(position);
                notifyItemRemoved(position);
                notifyDataSetChanged();


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


            }
        });


    }


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

    }

}

product.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>();





    @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

            }
        });








        //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(",");
                    //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的新功能-Suraj帮助

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

5 个答案:

答案 0 :(得分:2)

您在 public function middleware($middlewareQueue) { $middlewareQueue // Catch any exceptions in the lower layers, // and make an error page/response ->add(ErrorHandlerMiddleware::class) // Handle plugin/theme assets like CakePHP normally does. ->add(new AssetMiddleware([ 'cacheTime' => Configure::read('Asset.cacheTime') ])) // Add routing middleware. // Routes collection cache enabled by default, to disable route caching // pass null as cacheConfig, example: `new RoutingMiddleware($this)` // you might want to disable this cache in case your routing is extremely simple ->add(new RoutingMiddleware($this, '_cake_routes_')); // Add csrf middleware. // ->add(new CsrfProtectionMiddleware([ // 'httpOnly' => true // ])); return $middlewareQueue; } 中缺少if(isChecked) 您无需调用notifyDataSetChanged(),而使用getAdapterPosition()代替position。

OnCheckedChangeListener

将代码添加到 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){ productList.remove(getAdapterPosition()); notifyItemRemoved(getAdapterPosition()); Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show(); } } }); } 构造函数中

每次添加新产品时,您都需要创建新产品。

ProductViewHolder

关键是您需要使用新关键字创建新产品

答案 1 :(得分:1)

这里您要删除onBindViewHolder中的行,这就是造成问题的原因

第1步:

从OnBind删除onCheckedChangeLis

第2步

像这样在OnView持有人中执行OnCheckedChangeLis

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.

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


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


        }
    });

    }

    public View getView() {
        return rootView;
    }

}

希望这可以解决您的问题:)

答案 2 :(得分:1)

在您的viewholder类中,添加以下行checkBox.setChecked(false);

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);
        checkBox.setChecked(false);
        rootView = itemView.findViewById(R.id.linearLayout);
}

答案 3 :(得分:1)

答案 4 :(得分:0)

我认为这是recyclerview中的复选框选择问题。

将此链接添加到您的 $json_string = '[ {"id":14970, "amount":"70", "name":"Food" }, {"id":14970, "amount":"100", "name":"Drink" }, {"id":14970, "amount":"100", "name":"Food" }, {"id":14970, "amount":"300", "name":"Drink" }, {"id":14970, "amount":"10", "name":"Taxi" }, {"id":14970, "amount":"200", "name":"Food" } ]'; $array = json_decode($json_string, true); $result = array(); if (count($array) > 0) { foreach ($array as $value) { $name = $value['name']; $result[$name][] = $value; } } echo '<pre>'; print_r(array_values($result));

onBindViewHolder()

holder.checkBox.setChecked(false) // OR set logic for checkbox selection

希望这可能对您有所帮助:)