
2.2.2 DependentLayout
DependentLayout 在开发过程中也很常用,之前介绍的 DirectionalLayout通过方向、权重来控制内部组件的位置,而 DependentLayout 更为灵活,拥有更多的排列方式,它通过相对的方式来对组件进行定位,组件通过指定相对于其他组件的位置,可以出现在布局中的任何地方。
图2-18就是一个相对布局完成的页面,在页面中先摆放一个组件A,然后摆放组件B,让其位置在组件A下面。最后,摆放组件C,让组件C在组件A的下面,且在组件B的右侧。这样就通过相对位置的方式,完成了这个布局设计。
下面用XML布局文件的代码将其实现。


首先,为“按钮A”和“按钮B”增加一个ID,然后在设置“按钮B”的位置时,用了ohos:below属性,通过$id:A值告诉系统,“按钮B”的位置在“按钮A”的下面。
然后,在设置“按钮 C”的位置时,用了两个相对位置的描述,通过ohos:below="$id:A"指定“按钮 C”的位置在“按钮 A”的下面,通过ohos:right_of="$id:B"指定“按钮C”的位置在“按钮B”的右侧。这样就达到了指定“按钮C”的位置在“按钮A”的下面,同时又在“按钮B”的右侧的效果。页面的预览效果如图2-19所示。

图2-18 相对布局

图2-19 相对布局的例子
关于相对位置的属性有很多,表2-2列出了几个常用的属性和其对应的含义。
表2-2 关于相对位置的属性及含义

续表

下面通过一个小例子来更加清晰地认识这些属性的含义。这个案例是仿遥控器,在屏幕中摆放五个按钮,使用相对位置来确定各个按钮的位置。


在这个例子中,在DependentLayout中创建了五个按钮,首先来看“中间”按钮,它的位置用ohos:center_in_parent="true"来确定,表明它在父布局的中心。名称为“上面”的按钮在“中间”按钮的上面,并且在屏幕中水平居中,所以这里用到了两个定位方式:水平居中(ohos:horizontal_center="true")和在“中间”按钮上面(ohos:above="$id:A"),它的位置是依赖于“中间”按钮的。
“下面”按钮也需要依赖“中间”按钮来确定位置,通过ohos:below="$id:A"来确定在“中间”按钮下面,并通过水平居中(ohos:horizontal_center="true"),让其位于“中间”按钮的正下面。

图2-20 仿遥控器例子
“左侧”按钮在“中间”按钮的左侧,依赖于“中间”按钮的位置,通过ohos:left_of="$id:A"固定在“中间”按钮左侧,并通过垂直居中(ohos:vertical_center="true")固定在“中间”按钮的正左侧。
“右侧”按钮在“中间”按钮的右侧,依赖于“中间”按钮的位置,通过ohos:right_of="$id:A"和垂直居中(ohos:vertical_center="true")固定在“中间”按钮的正右侧。页面的预览效果如图2-20所示。
“中间”按钮位于屏幕的中心,其他四个按钮依赖于“中间”按钮摆放。因此在使用DependentLayout时,要首先明确组件之间的依赖关系,后面加入的组件依赖于前面组件的位置,这样可以实现丰富的布局设计。
虽然 DependentLayout 中关于位置的属性值很多,但是大部分都可以通过属性名得知,这是有一定规律的。
下面来看如何用Java代码实现相对布局。


在上述代码中,也使用了 LayoutConfig 对象来设置组件的属性,但此LayoutConfig对象和DirectionalLayout中使用的LayoutConfig对象不同,这一点要稍加注意。在DependentLayout中,可以通过LayoutConfig对象的addRule()方法来控制组件的位置和相对位置。