android 使用代碼實現 RelativeLayout布局

來源:互聯網
上載者:User

只需把代碼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);  

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.