Umair Iqbal
Umair Iqbal

Reputation: 2069

Set Id to dynamically created edittext

I'm dynamically creating Edittext on a button click and saving this edittext to an ArrayList of type Edittext and then getting values of all edittext in an ArrayList of type String. While creating new Edittext Iam also creating a BUTTON with cross image which delete that edittext when user click on it. and then Iam passing these edittexts to Options of CheckBox question which is also Iam creating dynamically. Issue is when I create multiple edittext and randomly delete someone and click ok arraylist remove the last index of it .Iam also setting ids to Edittext but couldnt able to understand how to get the Id of the same Edittext whose value I want to delete and then remove him from ArrayList too.

Here I'am creating the Edittext and adding them in "moreOptList" with there ids.

EditText checkBoxMoreEdt = new EditText(this);
 checkBoxMoreEdt.setId(i);
 moreOptList.add(i, checkBoxMoreEdt);

Here Iam deleting the view on Button clickListener,but instead of deleting the the exact value from arrayList also its only delete the view and the last index of array from the list.For example if I have enter 4 options a b c d and then deleted the option 2 which is b and click ok,it will show me a b c what its doing is removing the last save value from arrayList now How should I get the Id of exact edittext I want to delete and delete it from arrayList also.

final Button button = new Button(this);  
  button.setId(b);
  button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chkbParentLayout.removeView(ll);
                moreOptList.remove(i);
            }
        });

Upvotes: 1

Views: 195

Answers (1)

eleven
eleven

Reputation: 6847

Most probably the problem is in ArrayList. When you remove element by index all elements are shifted, hence indexes do not match your views:

list.add(0, 0) //[0]
list.add(1, 1) //[0, 1]
list.remove(0) //[1]
list.remove(1) //throws IndexOutOfBoundsException

One options is to replace ArrayList with HashMap:

map = HashMap<Integer, View>()
map.put(i, view)
...
group.remove(map.remove(i))

Another useful thing is to use setTag/getTag methods of View, you can store your indexes there, so you might not need to have external indexes storage:

view.setTag(index)
index = view.getTag()

Upvotes: 1

Related Questions