Reputation: 55
In my Android application, is there a way I can set the text to a textview by using a variable as part of the id?
I am trying to do something like this:
for (int i = 1; i < 6; i++){
views.setTextViewText(R.id.textView+i, "" + realtimeData.get(i).id);
}
I do have the TextViews declared in the layout xml as textView1, textView2, etc... and can access them with the static name. My issue is I do not know how many objects will be in my list. I do not want to display more than 5, but if there are fewer than 5 its ok for the TextView value to be left blank.
Upvotes: 4
Views: 3351
Reputation: 47471
Using getIdentifier()
was causing me grief so I ended up with the following:
String idName = "companyName"; // The id name of your resource.
int resourceId = R.id.class.getField(idName).getInt(null);
Upvotes: 0
Reputation: 3876
Provided you keep a thigh control over your R file to make sure your IDs are consecutive, you could try something like:
for (int i = R.id.firstTextView; i <= R.id.lastTextView; i++){
views.setTextViewText(i, "" + realtimeData.get(i).id);
}
which would allow to just add IDs to the R file without having to modify your code to change the hardcoded 6
number.
Just to prove my point:
<TextView android:id="@+id/testStart" />
<TextView android:id="@+id/test2" />
<TextView android:id="@+id/test3" />
<TextView android:id="@+id/testEnd" />
<Button android:id="@+id/button1" />
generates:
public static final int button1=0x7f070004;
public static final int menu_settings=0x7f070005;
public static final int test2=0x7f070001;
public static final int test3=0x7f070002;
public static final int testEnd=0x7f070003;
public static final int testStart=0x7f070000;
Adding at a later stage:
<TextView android:id="@+id/test4" />
right before
<TextView android:id="@+id/testEnd" />
immediately changes R.java to:
public static final int button1=0x7f070005;
public static final int menu_settings=0x7f070006;
public static final int test2=0x7f070001;
public static final int test3=0x7f070002;
public static final int test4=0x7f070003;
public static final int testEnd=0x7f070004;
public static final int testStart=0x7f070000;
Upvotes: -1
Reputation: 18863
+1 to Luksprog , However I feel that "i<6" isn't the right way to go, Instead use ViewGroup.getChildCount() and ViewGroup.getChildAt(int)
so you can control your amount of textviews better.
Upvotes: 2
Reputation: 87064
You're looking for the getIdentifier()
method:
for (int i = 1; i < 6; i++){
views.setTextViewText(getResources().getIdentifier("textView" + i, "id", getPackageName()), "" + realtimeData.get(i).id);
}
Upvotes: 7