2014-03-28 152 views
0

Android的布局,我想能够在我的布局环和文本添加到textviews动态,这并不会报错了,但我得到失去的行中的显示例如for循环文本

Tw04 One4 

我想是能够显示

One1 Two1 
One2 Two2 

等等

@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); 
    } 
} 
+1

你应该在'for'循环之前获得对TextViews的引用,然后使用'for'循环中的引用。 'findViewById()'是一个相对昂贵的方法调用。在一个简单的例子中,像你发布的示例一样重要,但如果你的数据集很大,它可能开始成为一个问题。 – FoamyGuy

回答

0

您可以以编程方式添加到TextViews如下布局:

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]); 
} 

其中linear是从布局的LinearLayout。

+0

感谢您的帮助Matt_9.0,这将工作,但挖掘周围后,我发现最好使用表格布局并从循环中添加行。但你明白了。 – thechrisberry

0

你只有两个文本v其中实际上您需要10个示例,每个项目要显示一个文本视图。我建议你改为ListView,列表中的每一行都是几个文本视图。