2012-07-14 23 views
5

Trong android, tôi có một khối mã:Làm cách nào để thêm nút động dưới chế độ xem khác?

// 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" 
/> 

Trong hoạt động của tôi, Với RelativeLayout.LayoutParam tôi có thể thêm các button ở vị trí left, right, top, bottom của root xem, nhưng tôi không thể thêm below hoặc vv ... của một góc nhìn khác !! Vì vậy, Bất kỳ ai cũng có thể đưa ra đề xuất để thêm view liên quan đến một view khác trong RelativeLayout động?

Trả lời

7

Thông tin cho bạn đây. Điều này sẽ thực hiện những gì bạn đang tìm kiếm để làm:

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

Cảm ơn, tôi sẽ thử !! –

+0

@KingfisherPhuoc bạn có thể vui lòng hướng dẫn làm thế nào tôi có thể đặt các nút động đa cấp với vị trí ngẫu nhiên trong một bố trí tương đối –

-1

Sử dụng

Button b=new Button(this); 

bạn phải tạo nút mới ... và chỉ cần thêm một bố trí trong main.xml sử dụng id của bố trí như

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

layout.add(R.id.button); 

bạn có thể làm điều này một cách dễ dàng để thêm nút động ..

+0

cảm ơn, nhưng đề xuất của bạn chỉ cần thêm nút trong 'LinearLayout'! Câu hỏi chính của tôi là 'làm thế nào để thêm một nút mà nên được dưới một EditView (hoặc bất kỳ Xem) trong RelativeLayout động? '! Dù sao, cảm ơn vì đã trả lời !! –

Các vấn đề liên quan