javaandroidxmlandroid-studioandroid-identifiers

How to create a dynamic variable name ? Android Studio id name problem


I am doing android and want to get id name's one by one so that I can display data on views in a correct order, so for that I saved the id's as (selected1, selected2, selected3, ...). Actually I want to name the selected item in MainActivity which is chosen by the user in SecondActivity and I get the name back in MainActivity using Intent.

And this is the MainActivity.xml code

But the problem is that I can't able to call id name dynamically of MainActivity's TextView like

int counter = 1;
// to count till which view we put the data,
// numbering is also related to name of id's you can see in image
String str_count = Integer.toString(counter);
String selected = "selected";
String id_name = selected + str_count;
// currently id_name = "selected1", I am going to increase this counter
// so next time we will get the next view

But it tells us to create new id with name id_name

And this is that problem


Solution

  • R.id.* is actually an integer value. You can get it with Resources#getIdentifier method.

    TextView place = findViewById(
        getResources().getIdentifier("selected" + counter, "id", getPackageName())
    );