(1)代码创建布局

  1. package com.code.hmdemo.slice;
  2. import ohos.aafwk.ability.AbilitySlice;
  3. import ohos.aafwk.content.Intent;
  4. import ohos.agp.components.*;
  5. public class MainAbilitySlice extends AbilitySlice {
  6. @Override
  7. public void onStart(Intent intent) {
  8. super.onStart(intent);
  9. // 创建button
  10. Button button1 = new Button(getContext());
  11. button1.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);//包住内容
  12. button1.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);//包住内容
  13. button1.setText("btn111");
  14. button1.setTextSize(25);
  15. Button button2 = new Button(getContext());
  16. button2.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);//
  17. button2.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
  18. button2.setText("btn222");
  19. button2.setTextSize(25);
  20. // 布局容器
  21. DirectionalLayout directionalLayout = new DirectionalLayout(getContext());
  22. directionalLayout.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);// 填充父容器
  23. directionalLayout.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);// 填充父容器
  24. directionalLayout.setOrientation(Component.VERTICAL);
  25. // 容器添加控件
  26. directionalLayout.addComponent(button1);
  27. directionalLayout.addComponent(button2);
  28. // 设置页面布局
  29. super.setUIContent(directionalLayout);
  30. }
  31. @Override
  32. public void onActive() {
  33. super.onActive();
  34. }
  35. @Override
  36. public void onForeground(Intent intent) {
  37. super.onForeground(intent);
  38. }
  39. }

(2)XML创建布局

第一步

  • 创建 resources/base/layout 文件夹,并新建main_layout.xml文件

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos"
    3. ohos:width="match_parent"
    4. ohos:height="match_parent"
    5. ohos:orientation="vertical">
    6. <Button
    7. ohos:width="match_parent"
    8. ohos:height="50vp"
    9. ohos:background_element="red"
    10. ohos:text="11111"
    11. />
    12. <Button
    13. ohos:width="match_parent"
    14. ohos:height="50vp"
    15. ohos:background_element="red"
    16. ohos:text="222"
    17. />
    18. </DirectionalLayout>

    第二步

  • 使用当前包名下的ResourceTable

  • 真正的资源id是 Layout_布局文件名 ``` package com.code.hmdemo.slice; import com.code.hmdemo.ResourceTable; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent;

public class MainAbilitySlice extends AbilitySlice {

  1. @Override
  2. public void onStart(Intent intent) {
  3. super.onStart(intent);
  4. super.setUIContent(ResourceTable.Layout_main_layout);
  5. }
  6. @Override
  7. public void onActive() {
  8. super.onActive();
  9. }
  10. @Override
  11. public void onForeground(Intent intent) {
  12. super.onForeground(intent);
  13. }

} ```