【发布时间】:2015-05-07 11:12:21
【问题描述】:
我试图了解<merge> 标签在内部是如何工作的。我使用View Hierarchy 工具研究了一些示例。所以我了解基本使用以及它如何在更高级别上工作,但我想更多地研究这个标签和一般的膨胀视图。
所以让我们考虑一些简单的布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/some_text"
android:text="@string/hello"
android:padding="10dp" />
</RelativeLayout>
当然还有 titlebar.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/chrome" />
</merge>
在这种情况下,我们有以下结果。
让我们改变我们的 titlebar.xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/some_text"
android:src="@drawable/chrome" />
结果真的来了。
让我们在 activity_main.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:background="@drawable/bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bug"
android:text="@string/hello"
android:padding="10dp" />
</LinearLayout>
而在 titlebar.xml 中,我保持一切不变。
所以在这种情况下,我们有一些奇怪的事情
1. 现在我们的根布局是LinearLayout。我们在标题栏文件中指定了不存在的属性android:layout_below="@+id/some_text"
- 在同一行中,我们有另一个问题
@+id/some_text不再存在,现在我们有@+id/bug。 我们来看看结果
这里我有一些问题:
我们可以在合并文件中使用任何属性(用于任何布局),但是如果包含此部分的视图组(布局)(在我们的例子中是 activity_main.xml)没有这样的属性,怎么办这种情况已经解决,只是我们在结果中看到的那样被忽略了吗?
我们在 imageview 上方硬编码了视图的 id,如果 id 存在,它就可以工作,但如果它不存在,正如我们在结果中看到的那样,它也被忽略了
所以我已经写了很多。 综上所述,XML解析器的工作与merge和include标签完全一致,也最好知道XML解析器的来源在哪里,看看它。
我将感谢所有阅读此行并可以提出建议或建议的人。
提前致谢。
【问题讨论】:
标签: android xml android-layout merge