2013-02-26 49 views

回答

22

創建/刪除按鈕的+ buttononClick- button如下:

public void onClick(View v) { 

    switch(v.getId()){ 
    case (R.id.plusbutton): 
       Button myButton = new Button(this); 
       myButton.setText("Add Me"); 

       LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout); 
       LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
       ll.addView(myButton, lp); 
       break;. 
    case (R.id.minusbutton): 
       Button myButton = new Button(this); 
       myButton.setText("Remove Me"); 

       LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout); 
       LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
       ll.removeView(myButton, lp); 
       break; 
      } 
     } 
+0

謝謝先生:)感謝您的幫助 – 2013-02-26 06:12:45

+3

buttonlayout是什麼?如何創建 – 2013-02-26 09:24:18

8

這是android系統中

LinearLayout row2 = (LinearLayout) findViewById(R.id.hll2); 
Button ivBowl = new Button(this); 
ivBowl.setText("hi"); 
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(70, 70); 
layoutParams.setMargins(5, 3, 0, 0); // left, top, right, bottom 
ivBowl.setLayoutParams(layoutParams); 
row2.addView(ivBowl); 
+1

+1很好的答案。 – Aravin 2013-09-05 13:30:25

+0

@Aravinth謝謝bro – Rohit 2013-09-06 04:54:02

3

這是很簡單的動態創建按鈕。

Button button1=new Button(context); 
    button1.setText("test"); 
    button1.setId(id); 
containerlayout.add(button1); 

希望這可以幫助你。

4
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.yourlayoutidthatisonethepicture); 

Button addButton =new Button(this); 
addButton.setText("add"); 

mainLayout.addView(addButton); 

除去僅僅是改變同一這種 「mainLayout.addView(addButton)」 到removeView或按鈕的setVisibility到View.GONE

+0

仍然沒有得到「R.id.yourlayoutidthatisonethepicture」請告訴我 – 2013-02-26 10:05:19

+0

完成:D謝謝你!喲天才:D – 2013-02-26 10:13:49

+0

很高興我可以幫忙;) – 2013-02-26 10:32:18

0

如果您想創建動態視圖(如EditText,textview等),那麼只需使用此代碼並在您的應用程序中運行它。

MyActivity.java://your的java文件

LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1); 
EditText et = new EditText(v.getContext()); 
et.setText("My new Edit Text); 
et.setMinLines(1); 
et.setMaxLines(3); 
ll.addView(et); 

在XML文件:

<LinearLayout 
android:id="@+id/linearLayout1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:layout_alignBottom="@+id/TextView01" 
android:layout_below="@+id/relativeLayout1" 
android:orientation="vertical" >