-3

I would like to create an array of EditText for android but it seems that finding the id has been a very challenging task.Can someone reach out?

My code for the array:

           EdiTText[]    mEditText = new EditText[20];
         for(int i =0;i<mEditText.length;i++){
            mEditText[i] = (EditText) findViewById(i);
             }
HRo
  • 115
  • 2
  • 9
  • What exactly are you trying to accomplish by doing this? Are you trying to create the `EditText`s programmatically or put existing ones into an `Array`? – codeMagic Apr 15 '13 at 13:58
  • anytime you are creating an Array of any type of View object you should be wondering to yourself if instead you ought to be using an AdapterView (like ListView) and a custom Adapter to achieve whatever it is you are after. Aside from that, Are you EditTexts declared in your layout file right now? – FoamyGuy Apr 15 '13 at 13:58
  • Did you have 20 EditTexts in your xml? if no mEditText[i] = (EditText) findViewById(i); - doesnt work and it is not necessary to use, because you already have 20 instance of EditText after EditText[] mEditText = new EditText[20]; – jimpanzer Apr 15 '13 at 13:59
  • you can get reference from this http://stackoverflow.com/questions/4394293/create-a-new-textview-programmatically-then-display-it-below-another-textview – Ronak Mehta Apr 15 '13 at 13:59

3 Answers3

0

You cannot set id to view in runtime. Read more about android id here. Just use constructor to initialize EditText:

mEditText[i] = new EditText(this);
amukhachov
  • 5,822
  • 1
  • 41
  • 60
0

There's two approaches to UI elements like EditText:

a. Implement them in your layout xml like this:

<EditText android:id="@+id/myedittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

Here the EditText would have the id "myedittext". You can then do stuff with that EditText by referencing it from your code with

EditText et = (EditText)findViewById(R.id.myedittext);

b. Programmatically create them like

EditText et = new EditText(context)

With this approach you will also have to manually add this EditText to your UI / layout.

You mixed those two approaches in a way that won't work.

If you don't know beforehand how many UI elements (in your case EditTexts) you need, it's cool to create them programmatically, but you should definitely read up on how to do that properly.

fweigl
  • 21,278
  • 20
  • 114
  • 205
0

I'm not going to ask why you're trying to do this. However...

The resource IDs needed by findViewById will not start at zero as implied by your code snippet which uses the loop index for id.

If the EditText are created in XML, then you need the resource IDs of the form R.id.xxxx. You could create an int[] of the IDs and pass the corresponding id to findViewById.

If you create the EditText in code, then you won't have IDs, so will have to store the EditText objects at creation time.

Graham Povey
  • 939
  • 8
  • 8