以编程方式将TextViews添加到XML布局

时间:2012-10-11 10:09:38

标签: android layout textview

这是XML LinearLayout linlayout.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之后,但不起作用。

2 个答案:

答案 0 :(得分: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]);
}

答案 1 :(得分: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);
}