通过代码生成上面的布局为:
1 package cn.android.codeui; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.view.ViewGroup.LayoutParams; 6 import android.widget.Button; 7 import android.widget.EditText; 8 import android.widget.LinearLayout; 9 import android.widget.TextView; 10 11 public class MainActivity extends Activity { 12 /** Called when the activity is first created. */ 13 @Override 14 public void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 17 LinearLayout linearlayout = new LinearLayout(this); 18 linearlayout.setOrientation(LinearLayout.VERTICAL); 19 20 TextView tv = new TextView(this); 21 tv.setText("姓名"); 22 LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 23 linearlayout.addView(tv, params); 24 25 EditText et = new EditText(this); 26 linearlayout.addView(et, params); 27 28 Button bt = new Button(this); 29 bt.setText("确定"); 30 params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 31 linearlayout.addView(bt, params); 32 33 params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 34 setContentView(linearlayout, params); 35 } 36 }
小结:一个控件只能有一个父元素,如果多次添加则会报出异常:
E/AndroidRuntime(23954):
java.lang.RuntimeException: Unable to start activity ComponentInfo{cn.android.codeui/cn.android.codeui.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.