Java – Android – Build dynamic forms from code

Android – Build dynamic forms from code… here is a solution to the problem.

Android – Build dynamic forms from code

I have to build a dynamic form in my activity based on the XML-populated data retrieved over HTTP.

This could be one or more RadioGroup, each with exactly three RadioButtons. After RadioGroups, I need to place two EditText and a CheckBox control with a submit button.

I

have prepared a LinearLayout with vertical orientation and unique ID that can be addressed from code, I hope I can create a form control in Java code without defining in android XML layout and adding to this linear layout.

I googled for hours and couldn’t find any examples of how to do this.

Can anyone provide some examples: how to create, for example, a RadioGruop and 1-2 RadioButtons and add them to LinearLayout (prepared in XML layout)?

Any suggestions !!! greatly appreciated

Solution

These widgets can be created just like other widgets:

final Context context; /* get Context from somewhere */
final LinearLayout layout = (LinearLayout)findViewById(R.id.your_layout);
final RadioGroup group = new RadioGroup(context);
final RadioButton button1 = new RadioButton(context);
button1.setId(button1_id);  this id can be generated as you like.
group.addView(button1,
    new RadioGroup.LayoutParams(
        RadioGroup.LayoutParams.WRAP_CONTENT,    
        RadioGroup.LayoutParams.WRAP_CONTENT));
final RadioButton button2 = new RadioButton(context);
button1.setId(button2_id);  this id can be generated as you like.
button2.setChecked(true);
group.addView(button2,
    new RadioGroup.LayoutParams(
        RadioGroup.LayoutParams.WRAP_CONTENT,    
        RadioGroup.LayoutParams.WRAP_CONTENT));
layout.addView(group,
    new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,    
        LinearLayout.LayoutParams.WRAP_CONTENT));

I haven’t tested this code, so it may contain some bugs. But I hope you will understand this.

Related Problems and Solutions