Elements overlapping in dynamically generated android layout
Elements overlapping in dynamically generated android layout
I am generating elements for a relative layout programmatically, catering for a different number of elements every time. I can make the TextView and EditText elements appear correctly, below one another without overlapping, but the second I added checkboxes and buttons everything became a mess. This is my code:
RelativeLayout mRlayout = (RelativeLayout) findViewById(R.id.checkFieldsLayout);
for (int i = 1; i < fields.size(); i++)
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.BELOW,fields.size()+i -1);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.BELOW, i);
String thisHeader = fields.get(i).replace("_", " ").toString();
if (thisHeader.contains("chkbox"))
CheckBox chkbox = new CheckBox(this);
chkbox.setId(i);
chkbox.setText(thisHeader);
chkbox.setLayoutParams(params1);
mRlayout.addView(chkbox);
if (thisHeader.contains("chkboximg"))
Button upload_btn = new Button(this);
upload_btn.setId(i);
upload_btn.setLayoutParams(params1);
upload_btn.setText("Select Image");
upload_btn.setOnClickListener(this);
mRlayout.addView(upload_btn);
else
TextView header = new TextView(this);
header.setText(StringUtils.capitalize(thisHeader));
header.setId(i);
header.setLayoutParams(params1);
EditText field = new EditText(this);
field.setLayoutParams(params2);
field.setId(fields.size() + i);
mRlayout.addView(header);
mRlayout.addView(field);
Can anyone figure out how to set up the layout parameters correctly so that each elements appears beneath the previous element?
1 Answer
1
You might be better off defining the view you're adding in XML and inflating them here rather than playing around with layout params in code. You can turn parts on and off by setting the visibility to Visible or Gone.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It can't be that complicated, I'm pretty sure it's a couple of layout rules that I'm missing.
– barnacle.m
Oct 22 '14 at 14:48