0

I have an ImageButton and when the user clicks on it an EditText is added to the layout. So what I want is that each EditText has a unique id.

a = 0;
imgAddText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       if (a <= 5) {
           layoutAddText.addView(createEditText());
           a++;
       }
    }
});

private EditText createEditText() {
    final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    final EditText editText = new EditText(this);
        return editText;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Nelson John
  • 144
  • 2
  • 16

3 Answers3

1

actually all view have setId method. You can make use of it.

setId(int id)

i would strong suggest you use setTag instead. I hope reason being your setting id is using same id to get it back by findViewId(int). Same thing you can achieve by findViewWithTag(Object tag)

Sush
  • 3,864
  • 2
  • 17
  • 35
  • When user clicks on button an ediitext is created. I want each edittext to have a unique id not the same. – Nelson John May 27 '16 at 07:38
  • I think depending on the use case, this answer is the most appropriate. – AL. May 27 '16 at 07:39
  • all the ids which are android generated will be long values and huge number. You can have for loop or your own unique number generation logic and set to edit text. – Sush May 27 '16 at 07:43
  • actually i know how to assign an id programatically but i am not able to figure out how to assign unique id to each newly created view. – Nelson John May 27 '16 at 07:44
  • oh.. well you can start from 1000 as example, then later more edittexts you wants to add just increase number by one.. like 1001,1002 – Sush May 27 '16 at 07:45
  • I was about to ask if i will be able to assign a number as id. I'll give it a try. @sush – Nelson John May 27 '16 at 07:46
  • yes you can.. i have worked on that part.. it works – Sush May 27 '16 at 07:54
0

In createEditText() method try this

    EditText editText=(EditText)findViewById(R.id.edit);
    editText.setLayoutParams(layoutParams);
    editText.setId(R.id.edit);
    return editText;
akhil Rao
  • 1,169
  • 7
  • 17
0

You can try setting tag instead of id as:

editText.setTag(UUID.randomUUID().toString());

or generate a unique id by creating a class say IdGenerator like:

public class IdGenerator() {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
    public static int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1;
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }
}

then do :

editText.setId(IdGenerator.generateViewId());
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64