如何在运行时添加TextView?

问题描述:

如何在运行时将新的TextView添加到布局中?可能吗?如何在运行时添加TextView?

编程添加TextView(或一般的View)到布局(或一般的ViewGroup)是可能的,请检查ViewGroup的public void addView (View child, int index)方法。

完整的解决方案:

View parent; //parent view where to add 


    ViewGroup layout=new LinearLayout(context); 
    layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
    TextView tv1=new TextView(context); 
    tv1.setText("Test1"); 
    TextView tv2=new TextView(context); 
    tv2.setText("Test2"); 
    layout.addView(tv1); 
    layout.addView(tv2); 
    parent.addView(layout); 
+1

哪里声明 “背景”?它在任何地方初始化 – 2013-11-26 09:00:50