0

I would like to be able to for loop in my layout and add text to the textviews dynamically, this does not error out but I get the lost row in the display for example

Tw04  One4

I would like to be able to display

One1 Two1
One2 Two2

etc...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rel_layout);
    for (int i = 0; i < 5; i++) {
        TextView woTxt = (TextView) findViewById(R.id.ticker_price);
        woTxt.setText("One"+i);
        TextView cusTxt = (TextView) findViewById(R.id.ticker_symbol);
        cusTxt.setText("Two"+i);
    }
}
Antony
  • 14,900
  • 10
  • 46
  • 74
thechrisberry
  • 177
  • 1
  • 18
  • 1
    You should get a reference to your TextViews before the `for` loop and then just use the reference that you have inside the `for` loop. `findViewById()` is a relatively expensive method call. It wont matter much in a trivial example like the sample you've posted but if your data set is large it could start to become an issue. – FoamyGuy Mar 28 '14 at 02:48

2 Answers2

0

You have only two text views, where in fact you need 10 on your example, one text view for each item you want to display. I suggest that you make a ListView instead, where each line of the list will be a couple of text views.

pmoo
  • 321
  • 1
  • 3
0

You may add TextViews programmatically to your layout as below :

TextView [] txt1 =new TextView[5];

for(int i=0;i<5;i++)
{
   txt1[i]=new TextView(YourActivity.this);
   txt1[i].setText("One"+i);
   txt1[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
   linear.addView(txt1[i]);
}

where linear is a LinearLayout from your layout.

  • Thanks for the help Matt_9.0, this would work but after digging around I found that it was best to use a table layout and add rows from the loop. But you get the points. – thechrisberry Mar 28 '14 at 13:08