(1)代码创建布局
package com.code.hmdemo.slice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// 创建button
Button button1 = new Button(getContext());
button1.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);//包住内容
button1.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);//包住内容
button1.setText("btn111");
button1.setTextSize(25);
Button button2 = new Button(getContext());
button2.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);//
button2.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
button2.setText("btn222");
button2.setTextSize(25);
// 布局容器
DirectionalLayout directionalLayout = new DirectionalLayout(getContext());
directionalLayout.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);// 填充父容器
directionalLayout.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);// 填充父容器
directionalLayout.setOrientation(Component.VERTICAL);
// 容器添加控件
directionalLayout.addComponent(button1);
directionalLayout.addComponent(button2);
// 设置页面布局
super.setUIContent(directionalLayout);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
(2)XML创建布局
第一步
创建 resources/base/layout 文件夹,并新建main_layout.xml文件
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:orientation="vertical">
<Button
ohos:width="match_parent"
ohos:height="50vp"
ohos:background_element="red"
ohos:text="11111"
/>
<Button
ohos:width="match_parent"
ohos:height="50vp"
ohos:background_element="red"
ohos:text="222"
/>
</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 {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_main_layout);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
} ```