public class CodeView extends Activity { //当第一次创建该Activity时回调该方法 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //创建一个线性布局管理器 LinearLayout layout = new LinearLayout(this); //设置该Activity显示layout super.setContentView(layout); layout.setOrientation(LinearLayout.VERTICAL); //创建一个TextView final TextView show = new TextView(this); //创建一个按钮 Button bn = new Button(this); bn.setText(R.string.ok); bn.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.WRAP_CONTENT)); //向Layout容器中添加TextView layout.addView(show); //向Layout容器中添加按钮 layout.addView(bn); //为按钮绑定一个事件监听器 bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { show.setText("Hello , Android , " + new java.util.Date()); } }); } }
1. bn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT ,
ViewGroup.LayoutParams.WRAP_CONTENT));
Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
一定要用父控件的LayoutParams。如果父控件是LinearLayout,当然就必须写成LinearLayout.LayoutParams,例如:
setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,TableRow.LayoutParams.FILL_PARENT));
这表示这个子控件的父布局是一个TableRow
2.new java.util.Date():显示当地时间