动态添加 View 到 Layout,务必先设定好 View 的外观,如 setText() 后,再使用 addView() 方法添加。
package com.ldq.add.text.view;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ExAddTextView extends Activity {
private LinearLayout layout;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (LinearLayout) findViewById(R.id.LinearLayout01);
for (int i = 0; i < 10; i++) {
TextView text = new TextView(this);
text.setText("第" + i + "个 TextView");
Log.i("------", text.toString());
layout.addView(text);
}
}
}