在运行时通过主内存中包含的 XML 字符串更改 activity 的布局

Change activity's layout by an XML string contained in main memory in runtime

我有一个 activity 正在显示给用户。在 activity 我有一个按钮。每次当用户按下按钮时,应用程序将从远程服务器加载一个 xml 文件。 xml 文件实际上是为应用程序设计的布局。在新 xml 文件加载并存储在 newLayout 变量后,我想设置 xml 文件以替换显示给用户的当前布局。

String newLayoutStr = "";
onClickButton() {
    newLayoutStr = loadNewLayoutFromRemoteServer();
}

// set the layout contained in newLayoutStr as new layout of the current activity

有意见吗?

我不确定这是否可以在运行时从内存中完成。您可以编组 XML 并将其保存到 SD 卡,然后使用 AssetManager

将其作为资源加载

从那里您可以使用 getLayoutInflater().inflate(YourResourceID, TheRootView)

给 XML 充气

据我所知,目前无法在运行时动态加载编译时不可用的布局。这是因为 LayoutInflater 需要一个资源 ID(来自 R class),这是在编译时确定的。另一种方法是实现自定义 LayoutInflater(通过借鉴 LayoutInflater class 的一些想法)可以做到这一点,尽管这将非常缓慢,因为在编译时完成了大量优化

根据您的要求,这是不可能的。 Android 依赖于使用自动生成的 class 调用 R 的资源标识符。该文件包含对应用程序中各种 class 值的 public static final int 引用。此处引用的 classes 可在 http://developer.android.com/reference/android/R.html

处找到

此 class 用于引用应用程序中的各种资源,其中之一是 layout。因此系统期望 xml 中定义的所有布局都包含在此生成的 R class.

所以一句话:你将无法按照你想要的方式完成这件事。

我会做的是 json 响应并将其转换为动态生成的布局。

XML 你下载test.xml

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_height="match_parent"
      android:layout_width="match_parent">

      <TextView android:id="@+id/textViewTest"
           android:layout_centerInParent="true"
           android:gravity="center"
           android:layout_height="wrap_content"
           android:layout_width="match_parent"/>

  </RelativeLayout>

如果您想在您的应用中创建此布局,请创建一个 json 响应:

{
"layout_parent":"RelativeLayout",
"layout_height": "match_parent",
"layout_width": "match_parent",
"layout_children": [
        {
            "layout_child":"TextView",
            "layout_child_id":"textViewTest",
            "layout_height":"wrap_content",
            "layout_width":"match_parent",
            "layout_gravity":"center",
            "layout_centerInParent":"true"
        }
    ]
}

然后我会将其解析为模型对象并使用该模型对象动态构建布局。为了添加字段,您需要在 xml 中定义一些布局,以便能够在您的应用中添加更多字段。