只需把代码copy进入oncreate方法即可运行

  1. RelativeLayout rl = new RelativeLayout(this);
  2. Button btn1 = new Button(this);
  3. btn1.setText("----------------------");
  4. btn1.setId(1);
  5. RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  6. lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
  7. lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
  8. // btn1 位于父 View 的顶部,在父 View 中水平居中
  9. rl.addView(btn1, lp1 );
  10. Button btn2 = new Button(this);
  11. btn2.setText("|\n|\n|\n|\n|\n|");
  12. btn2.setId(2);
  13. RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  14. lp2.addRule(RelativeLayout.BELOW, 1);
  15. lp2.addRule(RelativeLayout.ALIGN_LEFT, 1);
  16. // btn2 位于 btn1 的下方、其左边和 btn1 的左边对齐
  17. rl.addView(btn2, lp2);
  18. Button btn3 = new Button(this);
  19. btn3.setText("|\n|\n|\n|\n|\n|");
  20. btn3.setId(3);
  21. RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  22. lp3.addRule(RelativeLayout.BELOW, 1);
  23. lp3.addRule(RelativeLayout.RIGHT_OF, 2);
  24. lp3.addRule(RelativeLayout.ALIGN_RIGHT, 1);
  25. // btn3 位于 btn1 的下方、btn2 的右方且其右边和 btn1 的右边对齐(要扩充)
  26. rl.addView(btn3,lp3);
  27. Button btn4 = new Button(this);
  28. btn4.setText("--------------------------------------------");
  29. btn4.setId(4);
  30. RelativeLayout.LayoutParams lp4 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  31. lp4.addRule(RelativeLayout.BELOW, 2);
  32. lp4.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
  33. // btn4 位于 btn2 的下方,在父 Veiw 中水平居中
  34. rl.addView(btn4,lp4);
  35. setContentView(rl);

代码参考自:

http://hi.baidu.com/xiechengfa/blog/item/5a3570eb3afb1a31b90e2d54.html, 有改动

04-26 23:56