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

3
这是一个 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之后,但是无效。


你检查过文本视图的文本颜色是否与布局的背景颜色不同吗? - Paul
请删除 TextView txt =new TextView[3]; 并返回翻译后的文本。 - mukesh
TextView txt = new TextView[3]; 改为 TextView txt = new TextView[this]; - selva_pollachi
TextView[] txt = new TextView[3]; 这是一个包含3个TextView的数组。 - vpl
2个回答

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

我的代码没问题,只是在写帖子时出了错,我已经编辑过了,抱歉。 - vpl
我复制了你的代码并粘贴到我的应用程序中,它可以正常工作。 - Anil Jadhav
是的,它有效,谢谢。使用txt[i]=new TextView(YourActivity.this);很好用。 - vpl
如果这个可以正常工作,那么您必须接受这个作为正确的答案。 - Anil Jadhav
我正在尝试以编程方式添加TextView,但它无法正常工作。public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RelativeLayout rl = (RelativeLayout) findViewById(R.layout.activity_main); final TextView tv = new TextView(MainActivity.this); tv.setText("你好,世界"); tv.setTextColor(Color.BLACK); tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); rl.addView(tv); setContentView(R.layout.activity_main);} - FAISAL

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接