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.





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






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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)