1、在layout文件夾中通過xml文件創建
- 創建一個xml文件:例ability_demo.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="#000111"> </DependentLayout>
說明:DependentLayout 標簽是所有組件的承載體,所有組件都在該標簽里面
- 在DependentLayout標簽中插入文本組件
<Text ohos:id="$+id:text" ohos:width="match_content" ohos:height="match_content" ohos:text="你好,鴻蒙" ohos:text_color="#000000" ohos:text_size="32fp" ohos:center_in_parent="true"/>
說明:鴻蒙應用所有組件的屬性開始都是ohos:開始的(起始好像是harmonyos:開始,但是我接觸的時候是ohos) id(該組件的id),$+id指創建id為text的組件
- 創建DemoAilitySlice.java繼承AbilitySlice類,實現onStart方法來加載你定義好的布局:
public class DemoAbilitySlice extends AbilitySlice { @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_demo); // 加載xml布局 } }
- 在MainAbility中加載DemoAilitySlice類
public class MainAbility extends Ability { @Override public void onStart(Intent intent) { super.onStart(intent); super.setMainRoute(DemoAbilitySlice.class.getName()); //啟動時的第一個頁面 } }
2、直接在Slice中創建組件
- 在Slice中創建組件的時候就不用再加載xml文件,直接創建
public void onStart(Intent intent) { super.onStart(intent); // 聲明布局 DependentLayout myLayout = new DependentLayout(this); // 設置布局大小 myLayout.setWidth(MATCH_PARENT); myLayout.setHeight(MATCH_PARENT); // 設置布局背景為白色 ShapeElement element = new ShapeElement(); element.setRgbColor(new RgbColor(255, 255, 255)); myLayout.setBackground(element); // 創建一個文本 Text text = new Text(this); text.setText(intent.getStringParam("date")); text.setWidth(MATCH_PARENT); text.setTextSize(100); text.setTextColor(Color.BLACK); // 設置文本的布局 DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(MATCH_CONTENT,MATCH_CONTENT); textConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT); text.setLayoutConfig(textConfig); myLayout.addComponent(text); //將組件加入到布局頁面 super.setUIContent(myLayout); //加載布局 }