共计 1587 个字符,预计需要花费 4 分钟才能阅读完成。
作者:孔壹学院、程序咖创始人黎跃春。
收费零碎学习请移步:https://chengxuka.com
在上一节中,咱们用 XML 的形式编写了一个蕴含文本和按钮的页面。这一节咱们应用代码的形式编写第二个页面。
- 关上
src/main/java/com/example/myapplication/slice/MainAbilitySlice.java
文件,将上面的代码拷贝到外面。
package com.example.myapplication.slice; | |
import com.example.myapplication.ResourceTable; | |
import ohos.aafwk.ability.AbilitySlice; | |
import ohos.aafwk.content.Intent; | |
import ohos.agp.colors.RgbColor; | |
import ohos.agp.components.DependentLayout; | |
import ohos.agp.components.Text; | |
import ohos.agp.components.element.ShapeElement; | |
import ohos.agp.utils.Color; | |
import ohos.agp.components.DependentLayout.LayoutConfig; | |
public class MainAbilitySlice extends AbilitySlice { | |
@Override | |
public void onStart(Intent intent) {super.onStart(intent); | |
// 申明布局 | |
DependentLayout myLayout = new DependentLayout(this); | |
// 设置布局宽高 | |
myLayout.setWidth(LayoutConfig.MATCH_PARENT); | |
myLayout.setHeight(LayoutConfig.MATCH_PARENT); | |
// 设置布局背景为红色 | |
ShapeElement background = new ShapeElement(); | |
background.setRgbColor(new RgbColor(255, 255, 255)); | |
myLayout.setBackground(background); | |
// 创立一个文本 | |
Text text = new Text(this); | |
text.setText("www.chengxuka.com"); | |
text.setWidth(LayoutConfig.MATCH_PARENT); | |
text.setTextSize(100); | |
text.setTextColor(Color.BLACK); | |
// 设置文本的布局 | |
DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT); | |
textConfig.addRule(LayoutConfig.CENTER_IN_PARENT); | |
text.setLayoutConfig(textConfig); | |
myLayout.addComponent(text); | |
super.setUIContent(myLayout); // 加载 XML 布局 | |
} | |
} |
- 运行我的项目看成果。
入门系列
- HarmonyOS 鸿蒙开发:开发环境 DevEco Studio 装置
- 第二章 – HarmonyOS 鸿蒙开发:从 Hello Word 开始
- 第三章 – HarmonyOS 鸿蒙开发:3 分钟 XML 布局编写第一个页面
- 第四章 – HarmonyOS 鸿蒙开发:3 分钟 Java 代码编写第二个页面
- 第五章 – HarmonyOS 鸿蒙开发:3 分钟实现页面跳转
正文完