(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 {@Overridepublic void onStart(Intent intent) {super.onStart(intent);// 创建buttonButton 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);}@Overridepublic void onActive() {super.onActive();}@Overridepublic 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"><Buttonohos:width="match_parent"ohos:height="50vp"ohos:background_element="red"ohos:text="11111"/><Buttonohos: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 {
@Overridepublic void onStart(Intent intent) {super.onStart(intent);super.setUIContent(ResourceTable.Layout_main_layout);}@Overridepublic void onActive() {super.onActive();}@Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}
} ```
