必須使用relativelayout
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);//居中顯示。
layout.addView(button,lp);
同理 ,也可以設置其他對齊方式:
lp.addRule(RelativeLayout.ALIGN_WITH_PARENT_TOP);//父容器頂部對齊
lp.addRule(RelativeLayout.POSITION_BELOW,
view1);//與view1底部對齊
lp.addRule(RelativeLayout.ALIGN_LEFT, view2);//與view2左對齊