3

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?

2
  • 1
    Not without using reflection. Commented Nov 20, 2011 at 19:04
  • I agree with @Matt. As an alternative, You could use an array or List of TextViews. Or a Map where enums are the key and the associated TextViews the values. Commented Nov 20, 2011 at 19:13

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.