在 Java UI 框架中,提供了两种编写布局的方式:在XML中声明UI布局和在代码中创建布局。这两种方式创建出的布局没有本质差别,为了熟悉两种方式,我们将通过 XML 的方式编写第一个页面,通过代码的方式编写第二个页面。
Project”窗口,打开“entry > src > main > resources > base”,右键点击“base”文件夹,选择“New > Directory”,命名为“layout”。
layout”文件夹,选择“New > File”,命名为“main_layout.xml”。
在“layout”文件夹下可以看到新增了“main_layout.xml”文件。

main_layout.xml”文件,添加一个文本和一个按钮,示例代码如下:   xml version="1.0" encoding="utf-8"   <DependentLayout           xmlns:ohos="http://schemas.huawei.com/res/ohos"           ohos:width="match_parent"           ohos:height="match_parent"           ohos:background_element="#000000">       <Text               ohos:id="$+id:text"               ohos:width="match_content"               ohos:height="match_content"               ohos:center_in_parent="true"               ohos:text="Hello World"               ohos:text_color="white"               ohos:text_size="32fp"/>       <Button               ohos:id="$+id:button"               ohos:width="match_content"               ohos:height="match_content"               ohos:text_size="19fp"               ohos:text="Next"               ohos:top_padding="8vp"               ohos:bottom_padding="8vp"               ohos:right_padding="80vp"               ohos:left_padding="80vp"               ohos:text_color="white"               ohos:background_element="$graphic:button_element"               ohos:center_in_parent="true"               ohos:align_parent_bottom="true"/>   </DependentLayout>
button_element”来显示的,需要在“base”目录下创建“graphic”文件夹,在“graphic”文件夹中新建一个“button_element.xml”文件。
“button_element.xml”的示例代码如下:
   xml version="1.0" encoding="utf-8"   <shape           xmlns:ohos="http://schemas.huawei.com/res/ohos"           ohos:shape="oval">       <solid               ohos:color="#007DFF"/>   </shape>
Project”窗口中,选择“entry> src > main> java > com.example.helloworld > slice” ,打开“MainAbilitySlice.java”文件。onStart()方法加载 XML 布局,示例代码如下:   package com.example.myapplication.slice;       import com.example.myapplication.ResourceTable;   import ohos.aafwk.ability.AbilitySlice;   import ohos.aafwk.content.Intent;       public class MainAbilitySlice extends AbilitySlice {                  public void onStart(Intent intent) {           super.onStart(intent);           super.setUIContent(ResourceTable.Layout_main_layout); // 加载XML布局       }                  public void onActive() {           super.onActive();       }                  public void onForeground(Intent intent) {           super.onForeground(intent);       }   }
