java Android - 从代码构建动态表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5847561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - build dynamic form from code
提问by shadyyx
I have to build a dynamic form in my activity depending on the data retrieved via HTTP that is popullated from XML.
我必须根据从 XML 填充的 HTTP 检索到的数据在我的活动中构建一个动态表单。
This could be one or more RadioGroup
s each with exactly three RadioButton
s. After RadioGroups I need to place two EditText
and one CheckBox
control with submit button afterwards.
这可能是一个或多个RadioGroup
s,每个RadioButton
s正好是三个s。在 RadioGroups 之后,我需要用提交按钮放置两个EditText
和一个CheckBox
控件。
I have prepared a LinearLayout
with vertical orientation and unique ID to be addressed from code and I expect that I can create a form control within a Java code without defining in android XML layout and adding to this LinearLayout
.
我准备了一个LinearLayout
垂直方向和唯一 ID 的代码,我希望我可以在 Java 代码中创建一个表单控件,而无需在 android XML 布局中定义并添加到这个LinearLayout
.
I was googling for a few hours but could not find any example how to do this.
我在谷歌上搜索了几个小时,但找不到任何如何执行此操作的示例。
Could anyone please provide some example how to create e.g. one RadioGruop
with 1-2 RadioButton
s and add it to the LinearLayout
(that is prepared in XML layout)?
任何人都可以提供一些示例,例如如何创建一个RadioGruop
1-2RadioButton
秒并将其添加到LinearLayout
(以 XML 布局准备的)中?
Many thanks for any advice!!!
非常感谢您的任何建议!!!
回答by Michael
These widgets can be create like every 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 errors. But I hope you'll get the idea.
我还没有测试过这段代码,所以它可能包含一些错误。但我希望你能明白。