本文介绍了编程添加TextViews到XML布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个 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 添加的数量可以是不同的,有时

I want to add TextViews to this layout programmatically because the number of TextViews to be added can be different sometimes.

下面是活动code:

@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 当我运行的应用程序不会显示。

The LogCat don't display errors but the TextViews are not displayed when I run the app.

我尝试把行:

setContentView(R.layout.linlayout);

末,后,但不起作用。

推荐答案

使用这样的:

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

这篇关于编程添加TextViews到XML布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:58