hamid
hamid

Reputation: 2079

Looping through TextView and setting the text

I have exactly 20 TextView and their id is in sequence, i.e. :

R.id.textView1, R.id.textView2, R.id.textView3 ...

I have a for loop:

for (int i = 1; i < 21; i++) {
    TextView textView = (TextView) findViewById(R.id.textView ...);// 
    textView.setText("...");

is there a way to get TextView using this for loop and set their text?

Upvotes: 0

Views: 4481

Answers (3)

Philippe
Philippe

Reputation: 1307

This thread is very hold, but I faced the same sort of need : iterate through my layout structure and do something on each TextView. After having googlized it in many way, I finally decided to write my own implementation. You can find it here:

/*  Iterates through the given Layout, looking for TextView
    ---------------------------------
    Author : Philippe Bartolini (PhB-fr @ GitHub)
    Yes another iterator ;) I think it is very adaptable
*/

public void MyIterator(View thisView){
    ViewGroup thisViewGroup = null;
    boolean isTextView = false;
    int childrenCount = 0;

    try {
        thisViewGroup = (ViewGroup) thisView;
        childrenCount = thisViewGroup.getChildCount();
    }
    catch (Exception e){

    }

    if(childrenCount == 0){
        try {
            isTextView = ((TextView) thisView).getText() != null; // You can adapt it to your own neeeds.
        }
        catch (Exception e){

        }

        if(isTextView){
            // do something
        }
    }
    else {
        for(int i = 0; i < childrenCount; i++){
            MyIterator(thisViewGroup.getChildAt(i));
        }
    }
}

Upvotes: 0

Marcin S.
Marcin S.

Reputation: 11191

The more efficient way would be creating an array of integers and iterate through it:

int[] textViewIDs = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, ... };

for(int i=0; i < textViewIDs.length; i++) {
    TextView tv = (TextView ) findViewById(textViewIDs[i]);
    tv.setText("...");
}

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157437

if you gave to your TextView  as id R.id.textView1.. R.id.textView21, you ca use getIdentifier to retrieve the TextViews id from its name

for (int i = 1; i < 21; i++) {
String name = "textView"+i
int id = getResources().getIdentifier(name, "id", getPackageName());
 if (id != 0) {
     TextView textView = (TextView) findViewById(id); 
  }
}

Upvotes: 9

Related Questions