android 使用代码实现 RelativeLayout布局

只需把代码copy进入oncreate方法即可运行
Java代码  收藏代码
  1. RelativeLayout rl = new RelativeLayout(this);  
  2.          
  3.        Button btn1 = new Button(this);  
  4.        btn1.setText("----------------------");  
  5.        btn1.setId(1);  
  6.          
  7.        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);  
  8.        lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);  
  9.        lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);  
  10.        // btn1 位于父 View 的顶部,在父 View 中水平居中  
  11.        rl.addView(btn1, lp1 );  
  12.         
  13.        Button btn2 = new Button(this);  
  14.        btn2.setText("|\n|\n|\n|\n|\n|");  
  15.        btn2.setId(2);  
  16.         
  17.        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);  
  18.        lp2.addRule(RelativeLayout.BELOW, 1);  
  19.        lp2.addRule(RelativeLayout.ALIGN_LEFT, 1);  
  20.        // btn2 位于 btn1 的下方、其左边和 btn1 的左边对齐  
  21.        rl.addView(btn2, lp2);  
  22.         
  23.        Button btn3 = new Button(this);  
  24.        btn3.setText("|\n|\n|\n|\n|\n|");  
  25.        btn3.setId(3);  
  26.         
  27.        RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);  
  28.       lp3.addRule(RelativeLayout.BELOW, 1);  
  29.        lp3.addRule(RelativeLayout.RIGHT_OF, 2);  
  30.        lp3.addRule(RelativeLayout.ALIGN_RIGHT, 1);  
  31.        // btn3 位于 btn1 的下方、btn2 的右方且其右边和 btn1 的右边对齐(要扩充)  
  32.        rl.addView(btn3,lp3);  
  33.         
  34.        Button btn4 = new Button(this);  
  35.        btn4.setText("--------------------------------------------");  
  36.        btn4.setId(4);  
  37.         
  38.        RelativeLayout.LayoutParams lp4 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);  
  39.        lp4.addRule(RelativeLayout.BELOW, 2);  
  40.        lp4.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);  
  41.        // btn4 位于 btn2 的下方,在父 Veiw 中水平居中  
  42.        rl.addView(btn4,lp4);  
  43.         
  44.         
  45.        setContentView(rl);  



代码参考自:
http://hi.baidu.com/xiechengfa/blog/item/5a3570eb3afb1a31b90e2d54.html, 有改动
posted @ 2014-10-13 19:12  新感觉  阅读(694)  评论(0编辑  收藏  举报