HarmonyOS學習路之開發基礎——快速入門(實現頁面跳轉)

建立另一個頁面

在上一節中,我們用XML的方式編寫了一個包含文字和按鈕的頁面。為了幫助開發者熟悉在程式碼中建立佈局的方式,接下來我們使用程式碼的方式編寫第二個頁面。

在“Project”視窗,開啟“entry > src > main > java > com。example。myapplication”,右鍵點選“slice”資料夾,選擇“New > Java Class”,命名為“SecondAbilitySlice”,單擊回車鍵。

第二個頁面上有一個文字。在上一步建立的“SecondAbilitySlice”檔案中,新增一個Text,示例程式碼如下:

public class SecondAbilitySlice extends AbilitySlice {@Overridepublic 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(“Hi there”);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);}}

實現頁面跳轉

1、開啟第一個頁面的“MainAbilitySlice。java”檔案,新增按鈕的響應邏輯,實現點選按鈕跳轉到下一頁,示例程式碼如下:

public class MainAbilitySlice extends AbilitySlice {@Overridepublic void onStart(Intent intent) {super。onStart(intent);super。setUIContent(ResourceTable。Layout_ability_main);Button button = (Button) findComponentById(ResourceTable。Id_button);// 點選按鈕跳轉至第二個頁面button。setClickedListener(listener -> present(new SecondAbilitySlice(), new Intent()));}@Overridepublic void onActive() {super。onActive();}@Overridepublic void onForeground(Intent intent) {super。onForeground(intent);}}

2、再次執行專案,效果如下圖所示

HarmonyOS學習路之開發基礎——快速入門(實現頁面跳轉)