1

I have ten numberDecimal inputs with names input_1, input_2,...,input_10. In the mainActivity I'm getting theirs IDs by this way

EditText input_1 = (EditText) findViewById(R.id.input_1);
EditText input_2 = (EditText) findViewById(R.id.input_2);
...
EditText input_10 = (EditText) findViewById(R.id.input_10);

So I was wondering is there any way to get the IDs with FOR or any other cycle and arrays. For example something like this

for(i=1;i<10;i++) {
 EditText input_i = (EditText) findViewById(R.id.input_i);
}

I've tried this but it didn't work. Sorry for my english and thank you in advance :)

1
  • print the xml where you are using this. Commented Dec 15, 2013 at 15:44

3 Answers 3

1

You can use Context.getResources(), then Resources.getResourceIdentifier() to get the identifier of your edittext :

for(i=1;i<10;i++) {
    int resourceIdentifier = this.getResources().getResourceIdentifier("input_".concat(String.valueOf(i));
    EditText input_i = (EditText) findViewById(resourceIdentifier, "id", this.getPackageName()));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Create an Array of EditText and then Access this Array of EditText

Integer[] input_edit={R.id.input_1, R.id.input_2, R.id.input_3};


for (int i = 0; i < input_edit.length; i++) {
 EditText input = (EditText) findViewById(input_edit[i]);
**Then put this EditText Value in any Array if you need to work out side of this loop**         
}

Thanks

Comments

0

This is a efficient way of doing that. I used 2 methods, they are: getResource() and getIdentifier()

The first one is used to get access to the resources of your applicacion for example: you could use it to get a reference to a string using getResource().getString(id) or a drawable using getResource().getDrawable(id). You can get more info about its method here: Resources Documentation

The second one is a method from Resource class used to get an ID.

 EditText input;

for(int x = 0; x < 10; x++){

  //here you get the id

 int current_id =  this.getResources().getIdentifier("input_".concat(String.valueOf(i)), "id" ,getPackageName());

 //here you set the id
 input = (EditText) findViewById(current_id);

}

getIdentifier() needs 3 arguments and they are: (String name, String defType, String defPackage)

You can read about them here: Resource documentation (GetIdentifier() Method)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.