在应用程序启动时,我将从网络服务器下载数据并将其存储在共享首选项中,现在我想要的是根据 json 模板在 android 中动态创建 UI 表单/Activity 。任何人都可以建议我如何实现它。
{
"templates":[
{
"name":"Default",
"default":true,
"fields":[
{
"type":"textbox",
"label":"Your e-mail",
"metadataIPTC":"234",
"required":true,
"regex":"\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b"
}
]
}
]
}
最佳答案
XML 布局在运行时转换为 Java 对象,因此您可以简单地编写一个具有容器布局(例如 线性布局 )的 XML,在运行时将其膨胀,并根据从服务器收到的信息。
一个例子是:
创建布局,并将其设置为 Activity 的内容 View 。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/container"
/>
然后在代码的某处:
假设在解析 JSON 之后,您有一个 List
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
for (Field f: fields) {
if (f.getType().equals("textbox")) {
TextView txtView = new TextView(this);
txtView.setText("Your e-mail");
txtView.setId(1);//need for better use
linearLayout.addView(txtView);
} else if (f.getType().equals("button")) {
//create a button similarly as above,and add it to the layout
}
}
关于android - 从 json 模板在 Android 中创建动态 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923844/