Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Find an ID of dynamically created view

Tags:

find

android

view

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?

like image 854
Maciej Dobosz Avatar asked Jan 04 '23 04:01

Maciej Dobosz


1 Answers

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++;
}
like image 105
Robert Estivill Avatar answered Jan 14 '23 13:01

Robert Estivill