2013-12-23 67 views
1

我想在一個線性佈局內動態創建一個相對佈局。這個相對佈局包含一個文本視圖和按鈕,它們也是在動態方法中創建的。文本視圖和按鈕的對齊方式無法正常工作我試過的代碼在下面給出。android動態創建相互重疊的佈局

final LinearLayout lab_linear = (LinearLayout) findViewById(R.id.contact_list_layout); 
lab_linear.setOrientation(LinearLayout.VERTICAL); 
for (int i = 0; i < Size_contact; i++) 
{ 
    RelativeLayout layout = new RelativeLayout(this); 
    RelativeLayout.LayoutParams lp = new 
    RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT); 
    layout.setLayoutParams(lp); 

    final TextView Questions_value = new 
    android.widget.TextView(getApplicationContext()); 
    Questions_value.setText(contact_name.get(i)); 
    Questions_value.setTextSize(18); 
    Questions_value.setId(i); 
    layout.addView(Questions_value); 

    Button myButton = new Button(this); 
    myButton.setBackgroundResource(R.drawable.close); 
    myButton.setLayoutParams(new LayoutParams(20,20)); 
    layout.addView(myButton); 

    lab_linear.addView(layout); 
    } 

enter image description here

+0

你想要的佈局是什麼? – Gabe

+0

您並不特定於您的需求。 – AndroidHacker

回答

0

我可以建議使用LinearLayouts代替RelativeLayouts在你的循環?這樣,你就不會有重疊問題。

1

RelativeLayout單獨試試這個..

給佈局parems到TextViewButton並添加addRule(RelativeLayout.ALIGN_PARENT_RIGHT); or addRule(RelativeLayout.ALIGN_PARENT_LEFT);該意見

或添加以下爲Button

lp1.addRule(RelativeLayout.RIGHT_OF, Questions_value.getId());

for (int i = 0; i < Size_contact; i++) 
{ 
    RelativeLayout layout = new RelativeLayout(this); 
    RelativeLayout.LayoutParams lp = new 
    RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT); 
    lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 

    final TextView Questions_value = new 
    android.widget.TextView(getApplicationContext()); 
    Questions_value.setText(contact_name.get(i)); 
    Questions_value.setTextSize(18); 
    Questions_value.setId(i); 
    layout.addView(Questions_value,lp); 

    RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                   LayoutParams.WRAP_CONTENT); 
    lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
    //Or below remove above code and uncomment the below code 
    //lp1.addRule(RelativeLayout.RIGHT_OF, Questions_value.getId()); 
    Button myButton = new Button(this); 
    myButton.setBackgroundResource(R.drawable.close); 
    myButton.setLayoutParams(new LayoutParams(20,20)); 
    layout.addView(myButton,lp1); 

    lab_linear.addView(layout); 
    }