0

I've got this in my activity.java file.

    text[0] = (EditText) findViewById(R.id.editText2);
    text[1] = (EditText) findViewById(R.id.editText3);
    text[2] = (EditText) findViewById(R.id.editText4);
    text[3] = (EditText) findViewById(R.id.editText5);
    text[4] = (EditText) findViewById(R.id.editText6);
    text[5] = (EditText) findViewById(R.id.editText7);
    text[6] = (EditText) findViewById(R.id.editText8);
    text[7] = (EditText) findViewById(R.id.editText9);

How can I write it with a for loop.

 for(int i=o;i<8;i++)
 text[i] = (EditText) findViewById(R.id.<what here>);

How to reference edittext with index here?

Nikhil
  • 6,493
  • 10
  • 31
  • 68

3 Answers3

0

You can use a constant array for this.

// in your class 
private static final int[] TEXT_IDS = { R.id.editText2, R.id.editText3, ... , R.id.editText9};

//initializing
for(int i = o; i < TEXT_IDS.length; i++)
    text[i] = (EditText) findViewById(TEXT_IDS[i]);
Sipka
  • 2,291
  • 2
  • 27
  • 30
0

You can achieve this by using getIdentifier()

for(int i=0; i<8; i++) {
   for(int j=0; j<8; j++) {
    String editTextID = "btn" + i + "-" + j;
    int resID = getResources().getIdentifier(editTextID
    ,"id", "com.example.yourpackagename");
    buttons[i][j] = ((EditTextID) findViewById(resID));
   }
}
CodeWarrior
  • 5,026
  • 6
  • 30
  • 46
0

You could try something like the answer below, which is taken verbatim from here.

import java.lang.reflect.Field;
/* ... */

for (int i = 1; i < 16; i++) {
    int id = R.id.class.getField("s" + i).getInt(0);
    tv[i] = (TextView)findViewById(id);
    tv[i].setTypeface(face);
    tv[i].setClickable(true);
    tv[i].setOnClickListener(clickListener);
}
Community
  • 1
  • 1
crazylpfan
  • 1,038
  • 7
  • 9