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

标签 android android-layout

我有一个正在向用户显示的 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

有什么意见吗?

最佳答案

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

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

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

我会做的是有一个 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 中定义一些布局,以便能够在您的应用中添加更多字段。

关于android - 在运行时通过主内存中包含的 XML 字符串更改 Activity 的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29077321/

相关文章:

android - 数据库调用使 Android 应用程序崩溃

java - 不同屏幕尺寸的不同位置

java - 如何根据另一个 Activity 设置按钮不可见

android - 如何比较设置时间和实际时间?

android - 如何在android中的 View 上方添加阴影

android - 为 Android SDK 组织代码文件/XML 文件

android - 膨胀类 android.support.v7.widget.CardView ClassNotFoundException 时出错

java - Adapter 内的 ImageView 出现 NullPointerException

android - Android StackView 是什么样子的?

android - 将 Azure Easy 表与 SQL 数据库同步