Android - 从代码构建动态表单

sha*_*yyx 3 java forms android

我必须在我的活动中构建一个动态表单,具体取决于通过HTTP从XML中获取的数据.

这可以是一个或多个RadioGroups,每个恰好有三个RadioButtons.在RadioGroups之后,我需要在之后使用提交按钮放置两个EditText和一个CheckBox控件.

我准备了一个LinearLayout垂直方向和唯一ID来从代码中解决,我希望我可以在Java代码中创建一个表单控件,而无需在android XML布局中定义并添加到此LinearLayout.

我谷歌搜索了几个小时,但没有找到任何示例如何做到这一点.

任何人都可以提供一些示例如何创建例如RadioGruop1-2 RadioButton秒并将其添加到LinearLayout(在XML布局中准备)?

非常感谢任何建议!

Mic*_*ael 5

这些小部件可以像其他小部件一样创建:

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));
Run Code Online (Sandbox Code Playgroud)

我没有测试过这段代码,所以它可能包含一些错误.但我希望你能得到这个想法.