1、RelativeLayout布局
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
TextView mView = new TextView(this);
mView.setId(2);
mView.setText("this is a test text!");
layout.addView(mView);
Button btn=new Button(this);
btn.setText("调用子页面");
btn.setGravity(Gravity.CENTER);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
-2, -2);
// layoutParams.setMargins(100, 100, 100, 100);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);
layout.addView(mView, btn);
上例是将一个btn添加到RelativeLayout的底部。你可以把注释行取消掉,把下一行注释,再看下效果。
2、LinearLayout布局
LinearLayout linear=new LinearLayout(this);
linear.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setText("This is D Activity!");
tv.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.weight = 1.0f;
linear.setLayoutParams(lp);
linear.addView(tv,lp);//给TextView加Weight属性
//按钮没有设置Weight属性,将显示在最下面
Button btn=new Button(this);
btn.setText("调用子页面");
btn.setGravity(Gravity.CENTER);
linear.addView(btn);
btn.setOnClickListener(this);
setContentView(linear);