鴻蒙OS 組件與布局XML創(chuàng)建布局

2020-09-18 11:52 更新

XM L聲明布局的方式更加簡便直觀。每一個 Component 和 ComponentContainer 對象大部分屬性都支持在 XML 中進行設置,它們都有各自的 XML 屬性列表。某些屬性僅適用于特定的組件,例如:只有Text支持“text_color”屬性,但不支持該屬性的組件如果添加了該屬性,該屬性則會被忽略。具有繼承關(guān)系的組件子類將繼承父類的屬性列表,Component 作為組件的基類,擁有各個組件常用的屬性,比如:ID、布局參數(shù)等。

ID

  1. ohos:id="$+id:text"

在 XML 中使用此格式聲明一個對開發(fā)者友好的 ID,它會在編譯過程中轉(zhuǎn)換成一個常量。尤其在 DependentLayout 布局中,組件之間需要描述相對位置關(guān)系,描述時要通過 ID 來指定對應組件。

布局中的組件通常要設置獨立的 ID,以便在程序中查找該組件。如果布局中有不同組件設置了相同的 ID,在通過 ID 查找組件時會返回查找到的第一個組件,因此盡量保證在所要查找的布局中為組件設置獨立的 ID 值,避免出現(xiàn)與預期不符合的問題。

布局參數(shù)

  1. ohos:width="20vp"
  2. ohos:height="10vp"

與代碼中設置組件的寬度和高度類似,在 XML 中它們的取值可以是:

  • 具體的數(shù)值:10(以像素為單位)、10vp(以屏幕相對像素為單位)。
  • MATCH_PARENT:表示組件大小將擴展為父組件允許的最大值,它將占據(jù)父組件方向上的剩余大小,在 XML 中用“match_parent”表示。
  • MATCH_CONTENT:表示組件大小與它的內(nèi)容占據(jù)的大小范圍相適應,在 XML 中用數(shù)值“match_content”表示。

更多的組件屬性列表可參考組件的 XML 屬性文檔。

創(chuàng)建XML布局文件

  1. 在 DevEco Studio 的 “Project” 窗口,打開 “entry > src > main > resources > base”,右鍵點擊“base”文件夾,選擇“New > Directory”,命名為“l(fā)ayout”。

圖1 設置 Directory 名稱 img

  1. 右鍵點擊“l(fā)ayout”文件夾,選擇“New > File”,命名為“first_layout.xml”。

圖2 設置File名稱 img

修改XML布局文件

打開新創(chuàng)建的 first_layout.xml 布局文件,修改其中的內(nèi)容,對布局和組件的屬性和層級進行描述。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3. xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4. ohos:width="match_parent"
  5. ohos:height="match_parent"
  6. ohos:orientation="vertical"
  7. ohos:padding="32">
  8. <Text
  9. ohos:id="$+id:text"
  10. ohos:width="match_content"
  11. ohos:height="match_content"
  12. ohos:layout_alignment="horizontal_center"
  13. ohos:text="My name is Text."
  14. ohos:text_size="25vp"/>
  15. <Button
  16. ohos:id="$+id:button"
  17. ohos:width="match_content"
  18. ohos:height="match_content"
  19. ohos:layout_alignment="horizontal_center"
  20. ohos:text="My name is Button."
  21. ohos:text_size="50"/>
  22. </DirectionalLayout>

加載XML布局

在代碼中需要加載 XML 布局,并添加為根布局或作為其他布局的子 Component。

  1. @Override
  2. public void onStart(Intent intent) {
  3. super.onStart(intent);
  4. // 加載XML布局作為根布局
  5. super.setUIContent(ResourceTable.Layout_first_layout);
  6. // 查找布局中組件
  7. Button button = (Button) findComponentById(ResourceTable.Id_button);
  8. if (button != null) {
  9. // 設置組件的屬性
  10. ShapeElement background = new ShapeElement();
  11. background.setRgbColor(new RgbColor(0,125,255));
  12. background.setCornerRadius(25);
  13. button.setBackground(background);
  14. button.setClickedListener(new Component.ClickedListener() {
  15. @Override
  16. // 在組件中增加對點擊事件的檢測
  17. public void onClick(Component Component) {
  18. // 此處添加按鈕被點擊需要執(zhí)行的操作
  19. }
  20. });
  21. }
  22. }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號