什么是StackLayout

StackLayout又称层叠布局,其定位方式非常简单,所有控件都默认定位左上角.也支持将子控件显示在父控件的上下左右及正中间.

基础样例

1. 默认定位样例

效果图

零基础学鸿蒙编程-UI控件_StackLayout_零基础

代码

<?xml version="1.0" encoding="utf-8"?>
<StackLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent">

<Image
ohos:height="match_parent"
ohos:width="match_parent"
ohos:image_src="$media:beauty"/>

<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#000000"
ohos:layout_alignment="center"
ohos:text="花生皮编程"
ohos:text_color="#ffffff"
ohos:text_size="20fp"
ohos:top_margin="50vp"/>
</StackLayout>

2. 相对父控件定位

效果图

零基础学鸿蒙编程-UI控件_StackLayout_xml_02

代码

<?xml version="1.0" encoding="utf-8"?>
<StackLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="$media:beauty">

<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#000000"
ohos:layout_alignment="left"
ohos:text="左上"
ohos:text_color="#ffffff"
ohos:text_size="20fp"/>

<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#000000"
ohos:layout_alignment="right"
ohos:text="右上"
ohos:text_color="#ffffff"
ohos:text_size="20fp"/>

<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#000000"
ohos:layout_alignment="center"
ohos:text="正中间"
ohos:text_color="#ffffff"
ohos:text_size="20fp"/>

<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#000000"
ohos:layout_alignment="left|bottom"
ohos:text="左下"
ohos:text_color="#ffffff"
ohos:text_size="20fp"/>

<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#000000"
ohos:layout_alignment="right|bottom"
ohos:text="右下"
ohos:text_color="#ffffff"
ohos:text_size="20fp"/>
</StackLayout>

完整源代码

https://gitee.com/hspbc/harmonyos_demos/tree/master/stackLayoutDemo

常用属性说明

属性名

用途

ohos:width

设置控件宽度,可设置为:match_parent(和父控件一样),match_content(按照内容自动伸缩),设置固定值(如200vp)

ohos:height

设置控件高度,可设置为:match_parent(和父控件一样),match_content(按照内容自动伸缩),设置固定值(如200vp)

ohos:layout_alignment

在父控件内对齐方式,可选值:left:居左;start:居左;center:居中;right:居右;end:居右;top:居上;bottom:居下;horizontal_center:水平居中;vertical_center:垂直居中

ohos:background_element

设置背景,可以是色值(如#FF0000)或图片等

ohos:visibility

可选值: visible(显示), invisible(隐藏,但是仍占据UI空间),hide(隐藏,且不占UI空间)

更多属性及实际效果,可以在开发工具里自行体验.

零基础系列

《零基础学安卓编程》

《零基础学Java编程》

《零基础学鸿蒙编程》

关于我

厦门大学计算机专业 | 前华为工程师

专注《零基础学编程系列》,包含:Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙

全网可关注:花生皮编程

零基础学鸿蒙编程-UI控件_StackLayout_xml_03