0

So I'm creating an activity where users can create a poll.

I have:

1- Dynamically-added EditTexts

2- A List<EditText> allEds = new ArrayList<>(); that holds all the EditText views.

3- also dynamically attaching ImageButtons '❌' that work as a deletion tool attached on each and every EditText.

I simply want to:

Detect which EditText view the user deletes, in order to remove it synchronically from the allEds List.

In other words, when a user clicks on a deletion button attached to an EditText (besides deleting both views which I successfully did) I want to know which deletion button on which EditText was clicked and remove its whole value from the ArrayList.

Help me please.

  • Isn't the button id enough? – Zain Jun 06 '21 at 02:37
  • I tried this but the thing is how will I remove the same EditText from the ArrayList as there is no connection between the button id and the array serialization. So I thought why not use a counter++, it succeeded but I couldn't make it accurate, sometimes it throws an error (invalid index #, array size#), other times it removes the wrong value. – Mostafa Salem Jun 06 '21 at 02:44
  • Please show us the code of your attempt. We can't tell why there is "no connection " without seeing your code. Likewise we cannot explain the source of the errors if we can't see the code that generates them. – Stephen C Jun 06 '21 at 02:57

1 Answers1

0

You can use the EditText tag attribute by using view.setTag() method: So that each couple of Button & EdiText should have the same tag.

Then are a couple of options to link that to the list:

First one:

Make the tag value as an integer value that equals to the EditText index in the list: And remove it directly on the button click:

button.setOnClickListener(v -> {
    int buttonTag = (int) v.getTag();
    allEds.remove(buttonTag);
});

Second one:

Handling indexes in the first option can be a cumbersome, so you can just look for the intended tag by iterating over the list:

button.setOnClickListener(v -> {
    String buttonTag = (String) v.getTag();

    for(EditText editText: allEds) {
        String edtitextTag = (String) editText.getTag();
        if (buttonTag.equals(edtitextTag)) {
            // remove EditText
            allEds.remove(editText);
            break;
        }
    }
});
Zain
  • 37,492
  • 7
  • 60
  • 84
  • Can you please explain what EditText editText : allEds means? – Mostafa Salem Jun 06 '21 at 17:12
  • @MostafaSalem it is a forEach loop in java.. that means for each element (editText) in the list of elements (allEds) .. do the following... You can check [here](https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work) for more info – Zain Jun 06 '21 at 17:27