我必须根据从XML填充的通过HTTP检索的数据在 Activity 中构建动态表单。
这可以是一个或多个RadioGroup
,每个正好具有三个RadioButton
。在RadioGroups之后,我需要将两个EditText
和一个CheckBox
控件放置在提交按钮上。
我已经准备了一个具有垂直方向和唯一ID的LinearLayout
,可以通过代码进行寻址,并且我希望可以在Java代码中创建表单控件,而无需在android XML布局中定义并添加到此LinearLayout
中。
我在谷歌上搜索了几个小时,但是找不到如何执行此操作的任何示例。
任何人都可以提供一些示例,例如如何创建一个带有1-2 RadioGruop
的RadioButton
并将其添加到LinearLayout
(以XML布局编写)?
非常感谢您的任何建议!!!
最佳答案
这些小部件可以像其他所有小部件一样进行创建:
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));
我尚未测试此代码,因此可能包含一些错误。但我希望你能明白。