Android:用编程的方式开发UI组件

package com.example.codeview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 创建一个线性布局管理器
		LinearLayout layout = new LinearLayout(this);
		// 设置Activity显示Layout
		super.setContentView(layout);
		// 设置垂直布局方向
		layout.setOrientation(LinearLayout.VERTICAL);
		// 创建一个TextView
		final TextView show = new TextView(this);
		// 创建一个按钮
		Button btn = new Button(this);
		btn.setText(R.string.ok);
		btn.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT));
		// 向Layout容器中添加TextView
		layout.addView(show);
		// 向Layout容器中添加按钮
		layout.addView(btn);
		// 为按钮绑定一个事件监听器
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				show.setText("Hello,Android," + new java.util.Date());
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

相关推荐