I’m very new to android and trying to place the elements horizontally using android apis without xml.
What I’m trying to do is to place RadioButtons and EditText horizontally. Something like:
R-----E
R-----E
I tried code like this:
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
for(Map.Entry<String,String> entry : storedCards.entrySet())
{
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
EditText ed = new EditText(this);
RadioButton rb = new RadioButton(this);
rb.setId(counter++);
lp2.addRule(RelativeLayout.RIGHT_OF,rb.getId());
ed.setLayoutParams(lp2);
rg.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(entry.getKey());
relativeLayout.addView(ed);
}
This doesn’t work. But this is what I’m trying to do : First I’m setting the id for each radiobutton using the counter variable and trying to set edittext view on the right hand site of that radio button using:
lp2.addRule(RelativeLayout.RIGHT_OF,rb.getId());
But I’m not getting proper result. I get only like this:
ER
R
all EditText are being overlapped. Where I’m making the mistake?
Thanks in advance.
You cannot expect
RelativeLayoutto place views relative to other views that it does not contain. TheRelativeLayoutdoes not understand the ids of theRadioButtonsbecause they haven’t been added to it. Consequently, aRadioButtonadded to any other layout except forRadioGroup(which is just aLinearLayout) will not have the mutual exclusion logic you are probably looking for when the user taps them to be checked.So you must lay out your
RadioButtonitems in a verticalRadioGroup, and the simplest way to have yourEditTextitems line up next to them is to create a secondLinearLayoutnext to it, and use fixed height to ensure each “row” matches. Something like:This creates two side-by-side layouts that stay lined up due to the fixed item height. You can adjust the item height in the
LayoutParamsused for each row. You can see how doing layouts in pure Java is extremely verbose, which is the reason the preferred method is XML.