从recyclerview删除所有cardviews,然后添加新的cardviews-添加相同的cardviews [英] deleting all cardviews from recyclerview then adding new cardviews - adds same cardviews

查看:84
本文介绍了从recyclerview删除所有cardviews,然后添加新的cardviews-添加相同的cardviews的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When the user presses the FAB a cardview is added to the recyclerview. Inside each cardview is a checkbox. I want to make it so when the user ticks the checkbox in a specific cardview, that specific cardview is deleted.

(仅供参考,每个Cardview都有一个微调框和一个复选框,以及一个textview和edittext)

(FYI each cardview has a spinner and checkbox and a textview and edittext)

我按了四下晶圆厂以向屏幕添加4张卡片视图.然后,我从微调器中挑选了不同的东西,以查看发生了什么.当我勾选复选框时,该cardview将删除.我勾选了所有卡片视图的复选框,直到没有剩余卡片视图为止.

I pressed the fab 4 times to add 4 cardviews to my screen. i then picked different things from the spinner to see what was happening. When I tick the checkbox, that cardviewdeletes. I ticked the checkbox for all of the cardviews until I had no cardviews left.

但是当我去按下晶圆厂添加一个新的cardview时,我注意到cardview具有相同的选定微调器值,并且该复选框已被选中.例如,说我首先有一个带有土豆"的卡片视图,然后在其上打勾.现在屏幕上什么也没有.然后我按fab添加cardview.然后,我看到cardview上带有wlel的"potatoes",并且勾选了该复选框..如果那没有道理,请进行澄清

But then when I went to press the fab to add a new cardview, I noticed that that cardview has the same selected spinner value and the checkbox is already ticked..? For example say I firstly had a cardview which had 'potatoes' then I ticked that. Now therse nothing on my screen. then I press fab to add a cardview. Then I see that that cardview has 'potatoes' on it as wlel, and the checkbox is ticked..if that doesnt make sense, please ask for clarification

该怎么办?

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


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

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

            }
        });





    }


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


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

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

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



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

                }
            });



        }

        public View getView() {
            return rootView;
        }

    }

}

推荐答案

RecyclerView回收ViewHolders的性能. 这意味着,如果在微调器"中选择了"ViewHolder A",即使将其从列表中删除,它也不会被破坏.当您将新项目添加到列表中时,您的RecyclerView可能会对该项目重复使用"ViewHolder A",并且选择内容与上一个项目相同(删除之前).

RecyclerView recycles the ViewHolders for performance. This means, if the 'ViewHolder A' has 'option C' selected in your spinner, it won't be destroyed even if you remove the item from the list. When you add a new item to the list, your RecyclerView may reuse 'ViewHolder A' for that item, and the selection remains the same it was for your previous item (before it was deleted).

为避免这种情况,请使用LayoutManagerfindViewByPosition方法将新项添加到列表中时手动更新UI.

To avoid this, update your UI manually when you add a new item to the list using the findViewByPosition method of your LayoutManager.

示例:

// FAB button onClick method:
public void onClick(View v) {
    // Add item to RecyclerView list

    int itemPosition = myRecyclerViewAdapter.itemList.indexOf(newItem);
    ProductViewHolder vh = ((ProductViewHolder)recyclerView.getLayoutManager().findViewByPosition(itemPosition));

    // Here, set everything to the default values (unchecked checkbox, etc)
}

如果要将所有与RecyclerView相关的代码保留在适配器中(我鼓励您这样做),则可以在删除项目后将ViewHolder UI更新为默认值(而不是添加一个). ,因此您的ViewHolder很新鲜,可以用于下一个项目.

If you want to keep all RecyclerView related code in your Adapter (which I encourage you to do), you could update the ViewHolder UI to the default values after you delete your item (instead of when adding one), so your ViewHolder is fresh and ready for the next item.

示例(更好地使用此解决方案):

// Your positive button when deleting item onClick:
public void onClick(DialogInterface dialog, int id) {

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

    // Set spinner to default
    // Set checkbox to unchecked

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

这篇关于从recyclerview删除所有cardviews,然后添加新的cardviews-添加相同的cardviews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆