以下两个布局文件产生不同的结果:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<View
android:id="@+id/box"
android:background="#ff0000"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/next_box" />
<View
android:id="@+id/next_box"
android:background="#0000ff"
android:layout_width="60dp"
android:layout_alignParentRight="true"
android:layout_height="30dp"
/>
</RelativeLayout>
</LinearLayout>
结果:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<View
android:id="@+id/box"
android:background="#ff0000"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
/>
<View
android:id="@+id/next_box"
android:background="#0000ff"
android:layout_width="60dp"
android:layout_alignParentRight="true"
android:layout_height="30dp"
android:layout_toRightOf="@+id/box"
/>
</RelativeLayout>
</LinearLayout>
结果:
两种布局都试图描述相同的约束。即,红色矩形应接触父级的左边缘,蓝色矩形应接触父级的右边缘,并且它们应水平相邻出现。唯一的区别是您是否在红色矩形或蓝色矩形上指定“next to”约束。我找出了与通过形成约束的依赖图生成的测量分辨率顺序有关的原因,但我只是通过阅读RelativeLayout的源代码才弄清楚它,并且我找不到有关此行为的任何文档/注释。由于RelativeLayout一定是一个常用的布局组件,对于这种行为是否有更直观的解释,或者我是否缺少文档的某些部分?
最佳答案
尽管两者似乎都描述了相同的约束,但实际上并非如此。不同之处在于,一个说红色必须坐在蓝色旁边,而另一个说蓝色必须坐在红色旁边。一个意思是红色变蓝色的地方必须跟随,另一个意思是蓝色变红色的地方必须跟随,而且他们都想去不同的地方。
在第一个实例中,红色框依赖于蓝色框,因此首先构建蓝色框。蓝色盒子的宽度为60dp,因此首先构造一个60dp的蓝色盒子并右对齐。然后是红色盒子,它有一个限制位于蓝色盒子旁边。宽度 0 被忽略,因为它需要位于 60dp 蓝色旁边并左对齐。
在第二个实例中,蓝色框依赖于红色框,因此首先构建红色框。红框说它要0dp并左对齐,所以看不到。然后是蓝色框,它需要位于看不见的红色旁边并右对齐,从而占据整个空间,其宽度被忽略。
希望这是有道理的:)
关于android - Android 中的非对称relativelayout 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850772/