我正在尝试创建一个包含一组动态加载布局“页面”的程序。我使用每个页面共有的 View 的最小默认框架创建了基本布局。对于每个页面,我都将对所有要交换的 View 进行硬编码 (:facepalm)。我的下一个想法是创建一个文本文件并将必要的数据放入格式良好的设计中。直到那时我才意识到这正是 XML 文件的内容。所以我想做的是创建一个页面的 XML 文件,其中的数据与原始布局文件中的数据完全相同。然后在加载每个页面(可能卸载另一个页面)时,提取该页面的 XML 数据并将其插入到当前的基本布局结构中。
我的页面数据
<?xml version="1.0" encoding="utf-8"?>
<pageList>
<page:1>
<Button .../>
<EditText .../>
</page>
<page:2>
...
</pagelist>
基本 XML 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="1">
<LinearLayout android:id="@+id/linearLayout1"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="1.00" android:weightSum="1">
<EditText android:id="@+id/editText1" android:inputType="textMultiLine"
android:layout_width="0dp" android:layout_weight="0.30"
android:layout_height="match_parent"></EditText>
<RelativeLayout android:layout_width="0dp"
android:id="@+id/orientationLayout" android:layout_weight="0.70"
android:layout_height="match_parent">
<dynamically insert my PAGE here>
我是 Android 编程的新手,在从 XML 生成界面方面只有一点经验。在为之前的工作编写 C# 和 XML 时,我必须直接从嵌入式 XML 文件中提取数据,然后使用它自己创建 Button 或 TextBox。在这种情况下我需要做类似的事情还是有办法自动加载它?
我已经查了一段时间了,我在这个网站和其他地方找到的大多数答案都来自几个月前或更长时间。这些答案往往包括不可能自己做。我希望在过去的几个月里,系统可能发生了变化,但我还没有找到。
最佳答案
您可能正在寻找 ViewStub
.
A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The ViewStub then replaces itself in its parent with the inflated View or Views. [...]
您可以像布局中的普通 View 一样使用它,并使用 findViewById()
在代码中引用它。之后使用 ViewStub.setLayoutResource()
设置要显示的布局并调用 ViewStub.inflate()
显示它。这样你就可以写一个普通的XML
您需要的每个(子)页面的布局文件。
另见 this article .
编辑: 或者可能不会,我不得不提到 stub 在膨胀后从 View 层次结构中删除。因此,这是否有帮助取决于您的实际用例。
关于java - 将部分 XML 布局加载到 android 的就绪布局中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370043/