从 json 模板在 Android 中创建动态 UI

Create a Dynamic UI in Android from json Template

在应用程序启动时,我将从网络服务器下载数据并将其存储在共享首选项中,现在我想要的是根据 json 模板动态创建 UI form/Activity 在 android.Can 中有人建议我如何实现这个。

 {  
       "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 的内容视图。

<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
    }
  }

我想你问的是服务器驱动 UI,请通过这个 link 了解更多信息: https://proandroiddev.com/dynamic-screens-using-server-driven-ui-in-android-262f1e7875c1