android动态创建的布局相互重叠

时间:2013-12-23 07:16:45

标签: android android-layout textview android-button

我想动态地在线性布局中创建一个相对布局。这个相对布局包含一个文本视图和按钮,它们也是用动态方法创建的。文本视图和按钮的对齐不能正常工作。我试过的代码如下。

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

2 个答案:

答案 0 :(得分:1)

试试这个..

RelativeLayout的布局问题单独提供给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);
   }

答案 1 :(得分:0)

我建议你在循环中使用LinearLayouts而不是RelativeLayouts吗?这样,您就不会遇到重叠问题。