实例:
package com.ecainiao.code.drawlogin;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
private LinearLayout rot,row1,row2,row3;
private TextView tvName,tvPassword;
private EditText etName,etPassword;
private Button btnLogin,btnRegister;
//设置宽度和高度,权重的参数
private LayoutParams params;
public void setupView(){
//实例化控件和容器
params = new LayoutParams(0,LayoutParams.WRAP_CONTENT,1.0f);
rot = new LinearLayout(this);
rot.setOrientation(LinearLayout.VERTICAL);
row1 = new LinearLayout(this);
row1.setOrientation(LinearLayout.HORIZONTAL);
row2 = new LinearLayout(this);
row2.setOrientation(LinearLayout.HORIZONTAL);
row3 = new LinearLayout(this);
row3.setOrientation(LinearLayout.HORIZONTAL);
tvName = new TextView(this);
tvName.setText("用户名");
tvPassword = new TextView(this);
tvPassword.setText("密 码");
etName = new EditText(this);
etName.setLayoutParams(params);
etPassword = new EditText(this);
etPassword.setLayoutParams(params);
btnLogin = new Button(this);
btnLogin.setText("注册");
btnRegister = new Button(this);
btnRegister.setText("登录");
//组织视图树
row1.addView(tvName);
row1.addView(etName);
row2.addView(tvPassword);
row2.addView(etPassword);
row3.addView(btnLogin,params);
row3.addView(btnRegister,params);
rot.addView(row1);
rot.addView(row2);
rot.addView(row3);
//添加视图树到Activity区
setContentView(rot);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupView();
}
}