I’m working on Eclipse ADT. I came across task where I need to check a number of EditText fields, so I decided I could use FOR loop to check all of them with less coding.
For instance I have:
EditText editTxt1 = (EditText) findViewById(R.id.editText1);
EditText editTxt2 = (EditText) findViewById(R.id.editText2);
EditText editTxt3 = (EditText) findViewById(R.id.editText3);
EditText editTxt4 = (EditText) findViewById(R.id.editText4);
...
and I want to check them with for loop like so:
int x;
for (x=3; x<=4; x++) {
if (editTxt"x".getText().toString().equals("something")) do smthng...
}
Is it possible at all, or I have to go through long way coding?
You could do this via reflection as Quoi points out, but this is generally not a good a idea.
It would be better just to add your objects to a list or a map:
Now we can cycle through the list and use the index to check which edit text was being called.
You could also use a Map to do this, this would allow you to have a name value against your objects to help give you a better reference to check what object was being called. This takes a bit more work, but might be use
PS – Never use
==to compare Strings, it won’t always work!!