2012-10-11 49 views
3

这是一个XML LinearLayout linlayout.xml编程添加TextViews到XML布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/mylinear" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical"> 
</LinearLayout> 

我想补充TextViews到此布局编程,因为添加的TextViews的数量可以是不同的,有时。

下面是活动代码:

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.linlayout); 

    LinearLayout linear=(LinearLayout) findViewById(R.layout.mylinear); 
    TextView [] txt =new TextView[3]; 

    for(int i=0;i<txt.length;i++) 
    { 
     txt[i]=new TextView(this); 
     txt[i].setText("text "+i); 
     txt[i].setLayoutParams(new 
     LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
     linear.addView(txt[i]); 
    } 
} 

LogCat不显示错误,但TextViews当我运行的应用程序不会显示。

我尝试把线:

setContentView(R.layout.linlayout); 

末,该for后,但不起作用。

+0

您是否检查文本视图文本的颜色是否与布局的背景颜色不同? – Paul

+0

通过删除TextView来检查txt = new TextView [3]; – mukesh

+0

TextView txt = new TextView [3];通过TextView更改此行txt = new TextView [this]; –

回答

4

使用此:

TextView [] txt = new TextView[3]; 

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

在我的代码中,这是好的,当我写这篇文章时,只是一个错误,我编辑它,对不起。 – vpl

+0

我复制了你的代码并粘贴到我的应用程序中,它工作正常。 –

+0

你试试我的更新答案它有效100%。 –

1

这将是最好使用一个ListView。顺便说一下,您是否将布局的方向更改为垂直方向?但如果你需要我,我建议这个: 我想你有一定的大小的元素。

final int size = 3; // replace with the size of your element 
LinearLayout linear = (LinearLayout) findViewById(R.layout.mylinear); 

for(int i=0;i<size;i++){ 
    final TextView textView = new TextView(this); 
    textView.setText("text "+i); 
    textView.setLayoutParams(new LayoutParams(
    LayoutParams.FILL_PARENT, 
    LayoutParams.WRAP_CONTENT)); 

    linear.addView(textView); 
}