上文檔:git
HarmonyOS提供了Ability和AbilitySlice兩個基礎類。有界面的Ability綁定了系統的Window進行UI展現,且具備生命週期。AbilitySlice主要用於承載Ability的具體邏輯實現和界面UI,是應用顯示、運行和跳轉的最小單元。AbilitySlice經過setUIContent()爲界面設置佈局。github
組件須要進行組合,並添加到界面的佈局中。在Java UI框架中,提供了兩種編寫佈局的方式:框架
在代碼中建立佈局:用代碼建立Component和ComponentContainer對象,爲這些對象設置合適的佈局參數和屬性值,並將Component添加到ComponentContainer中,從而建立出完整界面。佈局
在XML中聲明UI佈局:按層級結構來描述Component和ComponentContainer的關係,給組件節點設定合適的佈局參數和屬性值,代碼中可直接加載生成此佈局。對象
這一次爲你們帶來的就是「在代碼中建立佈局」。blog
涵蓋核心知識點包括:(實戰Demo源碼地址:https://github.com/CoderMrYe/HarmonyStudy)生命週期
一、建立步驟:文檔
(1)聲明佈局get
DirectionalLayout directionalLayout = new DirectionalLayout(getContext());源碼
(2)設置佈局大小
directionalLayout.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT); directionalLayout.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
(3)設置佈局屬性及ID(ID視須要設置便可)
directionalLayout.setOrientation(Component.VERTICAL); directionalLayout.setPadding(32, 32, 32, 32);
(4)組件建立
Text text = new Text(getContext()); //組件初始化 text.setText("???");//組件屬性設置 text.setTextSize(50); text.setId(100);
(5)爲組件添加對應佈局的佈局屬性
DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT); layoutConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER; text.setLayoutConfig(layoutConfig);
(6)將組件添加到佈局中(多個組件,重複步驟456)
directionalLayout.addComponent(text);
(7)將佈局做爲根佈局添加到視圖樹中
super.setUIContent(directionalLayout);
本文由博客一文多發平臺 OpenWrite 發佈!