2012-07-14 87 views
5

在Android中,我有一個代碼塊:如何在另一個視圖下添加動態按鈕?

// RelativeLayout with id is "root": main.xml 
<EditText 
    android:id="@+id/pref_edit_text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:hint="Text to share in preference" 
/> 
// This is the button I want to add to main.xml 
<Button 
    android:id="@+id/save_button" 
    android:layout_below="@id/pref_edit_text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Save" 
/> 

在我的活動,隨着RelativeLayout.LayoutParam我可以在位置root鑑於left, right, top, bottom添加button,但我不能添加below或等...另一種觀點! 那麼,任何人都可以給出一個建議,在RelativeLayout中動態添加一個與view中的另一個view相關的view

回答

7

你在這裏。這將完成你正在做的事情:

public class ExampleActivity extends Activity { 
private RelativeLayout rl; 
private EditText editText; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_example); 

    rl = (RelativeLayout) findViewById(R.id.main_rl); 
    editText = (EditText) findViewById(R.id.pref_edit_text); 

    Button button = new Button(this); 
    button.setText("Save"); 

    // create the layout params that will be used to define how your 
    // button will be displayed 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
      LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

    // add the rule that places your button below your EditText object 
    params.addRule(RelativeLayout.BELOW, editText.getId()); 

    // set the layoutParams on the button 
    button.setLayoutParams(params); 

    // add button to your RelativeLayout 
    rl.addView(button); 
} 
} 
+0

謝謝,我會試試! – 2012-07-14 13:08:28

+0

@KingfisherPhuoc你可以請指導我如何將多個動態按鈕放置在相對佈局中的隨機位置 – 2017-02-02 12:08:28

-1

使用

Button b=new Button(this); 

你必須創建新的按鈕...並簡單地增加使用佈局 的ID main.xml中的佈局像

LinearLayout layout=(LinearLayout) findViewById(R.id.linear); 

layout.add(R.id.button); 

您可以輕鬆地做這件事情動態添加按鈕..

+0

謝謝,但你的建議只是在'LinearLayout'中添加一個按鈕!我的主要問題是'如何在RelativeLayout中動態添加一個Button應該位於EditView(或任何視圖)之下? '!無論如何,感謝您的迴應! – 2012-07-14 13:07:33