鴻蒙OS 創(chuàng)建另一個頁面

2020-09-15 10:37 更新

創(chuàng)建 Feature Ability

  1. 在“Project”窗口,打開“entry > src > main > java”,右鍵點(diǎn)擊“com.example.myapplication”文件夾,選擇“New > Ability > Empty Feature Ability(Java)”。

  1. 配置 Ability 時,將“Page Name”設(shè)置為“SecondAbility”,點(diǎn)擊“Finish”。創(chuàng)建完成后,可以看到新增了“SecondAbility”和“SecondAbilitySlice”文件。

img

代碼編寫界面

在上一節(jié)中,我們用 XML 的方式編寫了一個包含文本和按鈕的頁面。為了幫助開發(fā)者熟悉在代碼中創(chuàng)建布局的方式,接下來我們使用此方式編寫第二個頁面。

打開 “SecondAbilitySlice.java”文件,添加一個文本,示例代碼如下:

  1. package com.example.myapplication.slice;
  2. import ohos.aafwk.ability.AbilitySlice;
  3. import ohos.aafwk.content.Intent;
  4. import ohos.agp.colors.RgbColor;
  5. import ohos.agp.components.DependentLayout;
  6. import ohos.agp.components.DependentLayout.LayoutConfig;
  7. import ohos.agp.components.Text;
  8. import ohos.agp.components.element.ShapeElement;
  9. import ohos.agp.utils.Color;
  10. import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;
  11. import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
  12. public class SecondAbilitySlice extends AbilitySlice {
  13. @Override
  14. public void onStart(Intent intent) {
  15. super.onStart(intent);
  16. // 聲明布局
  17. DependentLayout myLayout = new DependentLayout(this);
  18. // 設(shè)置布局大小
  19. myLayout.setWidth(MATCH_PARENT);
  20. myLayout.setHeight(MATCH_PARENT);
  21. ShapeElement element = new ShapeElement();
  22. element.setRgbColor(new RgbColor(0, 0, 0));
  23. myLayout.setBackground(element);
  24. // 創(chuàng)建一個文本
  25. Text text = new Text(this);
  26. text.setText("Nice to meet you.");
  27. text.setWidth(MATCH_PARENT);
  28. text.setTextSize(55);
  29. text.setTextColor(Color.WHITE);
  30. // 設(shè)置文本的布局
  31. DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(MATCH_CONTENT,MATCH_CONTENT);
  32. textConfig.addRule(LayoutConfig.CENTER_IN_PARENT);
  33. text.setLayoutConfig(textConfig);
  34. myLayout.addComponent(text);
  35. super.setUIContent(myLayout);
  36. }
  37. @Override
  38. public void onActive() {
  39. super.onActive();
  40. }
  41. @Override
  42. public void onForeground(Intent intent) {
  43. super.onForeground(intent);
  44. }
  45. }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號