Question

I have code like this:

TextView wyniszczenie_zakres_bmi = (TextView)t.findViewById(R.id.wyniszczenie_zakres_bmi);
TextView wychudzenie_zakres_bmi = (TextView)t.findViewById(R.id.wychudzenie_zakres_bmi);
TextView niedowaga_zakres_bmi = (TextView)t.findViewById(R.id.niedowaga_zakres_bmi);

Can I do something like this?

List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");

for(String s : arStan){
    TextView s + _zakres_bmi = (TextView)t.findViewById(R.id. + s + _zakres_bmi);
}

I know it's not work but is there any solution for this?

Was it helpful?

Solution

Try this:

List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");

for(String s : arStan) {
    int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
    TextView myTextView = (TextView)t.findViewById(myId);
    // Do something with myTextView
}

If you need to save the textView references for later rather than acting on them immediately, then put myTextView into an array or hashtable after it's assigned.

Hashtable textViews = new Hashtable<String, TextView>();
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");

for(String s : arStan) {
    int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
    TextView myTextView = (TextView)t.findViewById(myId);
    textViews.put(s + "_zakres.bmi", myTextView);
}

// When you need to get one of the TextViews:
TextView tv = textViews.get("niedowaga_zakres.bmi");
// Do something with tv.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top