效果图:

具体步骤:
[$]
在 “Project” 窗口,打开 entry > src > main > java ,然后右击 com.example.helloword 文件夹,选择 New > Ability > Empty Page Ability (java)

然后 将“Page Name”设置为“MeAbility”,点击“Finish”。创建完成后,可以看到新增了“MeAbility”和“MeAbilitySlice”文件。 如下图所示:


打开 MeAbilitySlice.java 文件,通过代码的方式,添加一个文本,如下代码:
package com.example.helloword.slice; import com.example.helloword.ResourceTable; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.components.DependentLayout; import ohos.agp.components.Text; import ohos.agp.utils.Color; public class MeAbilitySlice extends AbilitySlice { @Override public void onStart(Intent intent) { super.onStart(intent); // 创建一个相对布局 DependentLayout dependentLayout = new DependentLayout(this); /* 设置文本的布局参数 DependentLayout.LayoutConfig.MATCH_CONTENT 表示宽度和高度都填充父容器 */ DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_CONTENT,DependentLayout.LayoutConfig.MATCH_CONTENT); // 添加布局规则 为 将子元素位于父元素的中心位置 layoutConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT); /* * 创建一个Text组件 * */ Text text = new Text(this); text.setWidth(DependentLayout.LayoutConfig.MATCH_CONTENT); // 设置Text 组件的宽度 text.setHeight(DependentLayout.LayoutConfig.MATCH_CONTENT); // 设置 Text 组件的高度 text.setText("蹦下嘎啦嘎"); // 设置要显示的文本 text.setTextColor(Color.RED); // 设置文字的颜色 text.setTextSize(50); // 设置文字的大小 // 设置 text 组件的布局配置 text.setLayoutConfig(layoutConfig); // 将Text 组件添加到 相对布局(dependentLayout) 中 dependentLayout.addComponent(text); // 将当前创建的相对布局作为根组件添加进去 super.setUIContent(dependentLayout); } @Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); } }
效果图:

[/$]