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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:05:54  来源:igfitidea点击:

Android - build dynamic form from code

javaandroidforms

提问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 RadioGroups each with exactly three RadioButtons. After RadioGroups I need to place two EditTextand one CheckBoxcontrol with submit button afterwards.

这可能是一个或多个RadioGroups,每个RadioButtons正好是三个s。在 RadioGroups 之后,我需要用提交按钮放置两个EditText和一个CheckBox控件。

I have prepared a LinearLayoutwith 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 RadioGruopwith 1-2 RadioButtons and add it to the LinearLayout(that is prepared in XML layout)?

任何人都可以提供一些示例,例如如何创建一个RadioGruop1-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.

我还没有测试过这段代码,所以它可能包含一些错误。但我希望你能明白。