android的UI布局有两种方式:
一、 通过xml文件来配置(如main.xml)
protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.g2); final TextView tView=(TextView)findViewById(R.id.t1); Button button1=(Button)findViewById(R.id.button9); Button button2=(Button)findViewById(R.id.button10); button2.setOnClickListener(new OnClickListener() { public void onClick(View v) {
tView.setTextColor(Color.GRAY); } }); }
或者定期activity的private变量
protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState);
setContentView(R.layout.g2);
注意:只有在加载指定的layout的后才可以通过该layout实例化 tView=(TextView)findViewById(R.id.t1); button1=(Button)findViewById(R.id.button9); button2=(Button)findViewById(R.id.button10);
setButton1(); setButton2(); }
private TextView tView; private Button button1; private Button button2;
二、 通过自定义
private LinearLayout mylayout;
private LinearLayout.LayoutParams layoutP;
private int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private TextView tv;
private Button button1;
private Button button2;
private Button button3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* 实例化一个LinearLayout布局对象*/
myLayout = new LinearLayout(this);
/* 设置LinearLayout的布局为垂直布局*/
myLayout.setOrientation(LinearLayout.VERTICAL);
/* 设置LinearLayout布局背景图片*/
myLayout.setBackgroundResource(R.drawable.back);
/* 加载主屏布局*/
setContentView(myLayout);
/* 实例化一个LinearLayout布局参数,用来添加View */
layoutP = new LinearLayout.LayoutParams(WC, WC);
tv=new TextView(this);
mylayout.addView(tv, layoutP);
}