I've got a following problem:
In Android Studio I generate en EditText
dynamically when an ExerciseButton
is clicked:
public void exerciseButtonClick(View view) {
EditText exercise = new EditText(this);
exercise.setId(exerciseId);
exerciseId++;
}
Later in the code I would like to refer to all my EditText
's via ID. I'm trying something like this but this is not working:
for (int i = 1; i < exerciseId; i++) {
EditText currentEditText = (EditText) findViewById(i);
// further instructions on that EditText
}
The error is of course here: findViewById(i)
, showing Expected resource type to be on of id. How can I solve this problem?
You need to make sure the ID
doesn't clash with the Android generated id's. Also, you need to make sure you add the views to the activity view hierarchy, otherwise they will never be found.
In your scenario, i would probably try one of the following things
1) If you still want to use integer id's, then use this method to generate a valid non-clashing id
https://developer.android.com/reference/android/view/View.html#generateViewId
2) Set tag
to the view, and retrieve by tag
. Tag can be any object.
public void exerciseButtonClick(View view) {
EditText exercise = new EditText(this);
exercise.setTag("exercise-" + excersiceId);
excersiceId++;
}
EditText exercise = (EditText)findViewByTag("exercise-" + someId );
3) Keep a local variable, holding the reference to the created EditText (or to the created array of EditTexts)
private EditText exercise;
public void exerciseButtonClick(View view) {
exercise = new EditText(this);
excersiceId++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With