动态地将textview添加到线性布局

时间:2012-08-16 06:28:50

标签: android android-layout android-linearlayout textview

我想将textview动态添加到线性布局中。

我使用了以下代码:

    LinearLayout ll = (LinearLayout)findViewById(R.id.viewlayout);
    LinearLayout.LayoutParams lp = new    LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    TextView tv = new TextView(viewrecords.this);
    tv.setId(1);
    tv.setTextSize(15);
    tv.setText("test adding");
    tv.setLayoutParams(lp);
    ll.addView(tv);

我没有添加textview。任何人都可以帮我解决问题。

1 个答案:

答案 0 :(得分:3)

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.rainbow);
TextView tv1 = new TextView(this);
tv1.setText("FIRST");
tv1.setTextSize(10);
tv1.setGravity(Gravity.CENTER);

TextView tv2 = new TextView(this);
tv2.setTextSize(10);
tv2.setGravity(Gravity.CENTER);
tv2.setText("MIDDLE");

TextView tv3 = new TextView(this);
tv3.setTextSize(10);
tv3.setGravity(Gravity.CENTER);
tv3.setText("LAST");

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
ll.setGravity(Gravity.CENTER);
ll.addView(tv1);
ll.addView(tv2);
ll.addView(tv3);    
setContentView(ll);
}

请参阅此示例,我们有明确的想法http://mobile.tutsplus.com/tutorials/android/android-sdk_linear-layouts_2/