Paul Esteban Milan
Paul Esteban Milan

Reputation: 109

Can I use a string as an Id?

Still a Noob at Android Development.. So here's My Code

for(int i=1;i<=6;i++){
    for(int j=startat;j<=7;j++){
        String constring = "r" + i + "c" + j;
        //TextView dtv = (TextView) findViewById(R.id.constring); #commented this out
    }
}

Is there a way I could use the string variable constring as an Id?

Upvotes: 1

Views: 123

Answers (2)

Simon Dorociak
Simon Dorociak

Reputation: 33515

Is there a way I could use the string variable constring as an Id?

I'm little confused what are trying to make?!

This: TextView dtv = (TextView) findViewById(R.id.constring);

especially R.id.constring you shouldn't, musn't do it in the way you do. Every id is automatic generated from XML resources and you should respect it!

Also R.id.costring is int auto-generated in R.java not String so your approach won't work.

From your code is feel "spaghetti code".

<TextView 
   android:id=@+id/constring"
   ... next attributes
/>

If you'll write this, id named as constring will be automatic generated and then you just call R.id so constring is automatic filled.

It a case if you don't want to create XML so you just do it like that:

TextView t = new TextView();
t.setText("Hello World");
setContentView(t);


I recommend to you read some Android tutorials for beginners. Here you can start:

Upvotes: 1

gpunto
gpunto

Reputation: 2852

You can use getIdentifier method to obtain resource id from name.

Upvotes: 0

Related Questions