在Java UI框架中,提供了两种编写布局的方式:在XML中声明UI布局和在代码中创建布局。这两种方式创建出的布局没有本质差别,为了熟悉两种方式,我们将通过XML的方式编写第一个页面,通过代码的方式编写第二个页面。
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”的示例代码如下(如果DevEco Studio提示xmlns字段错误,请忽略,不影响后续操作):<?xml version="1.0" encoding="utf-8"?> <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="oval"> <solid ohos:color="#007DFF"/> </shape>
加载XML布局
- 在“Project”窗口,选择“entry > src > main > java > com.example.myapplication > slice” ,打开“MainAbilitySlice.java”文件。
- 重写onStart()方法加载XML布局,示例代码如下(如果DevEco Studio提示Layout_main_layout错误,不影响后续操作,运行应用后即可消除):
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 { @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_main_layout); // 加载XML布局 } @Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); } }
- 请参考应用运行,效果如图所示: