Search code examples
androidandroid-view

How to delete edittext dynamically everytime I click a button


I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.


// Add On
        addOnLayout.removeAllViews();
        addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddOnCounters++;

                etFoodName = new EditText(addfoodAddOn.this);
                etFoodName.setId(ETFoodID);

                etFoodName.setHint("Enter your AddOn Name");

                etPrice = new EditText(addfoodAddOn.this);
                etPrice.setId(ETPriceID);
                etPrice.setHint("Enter your AddOn Price");

                Log.d("-------","-------------------what is edittext name id " + ETFoodID);
                Log.d("-------","-------------------what is edittext price id " + ETPriceID);

                ETFoodID++;
                ETPriceID++;


                addOnLayout.addView(etFoodName);
                addOnLayout.addView(etPrice);





            }
        });

        removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){


                    addOnLayout.removeViewAt(ETFoodID);
                    addOnLayout.removeViewAt(ETPriceID);
                    ETFoodID--;
                    ETPriceID--;

                }
            }
        });

I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.


Solution

  • Replace your listener

    removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){
                    View v1 = addOnLayout.findViewById(ETFoodID);
                    View v2 = addOnLayout.findViewById(ETPriceID);
                    addOnLayout.removeView(v1);
                    addOnLayout.removeView(v2);
                    ETFoodID--;
                    ETPriceID--;
    
                }
            }
        });