HarmonyOS學(xué)習(xí)路之開發(fā)基礎(chǔ)—快速入門(創(chuàng)建另一個(gè)頁(yè)面)
1
創(chuàng)建另一個(gè)頁(yè)面
在上一節(jié)中,我們用XML的方式編寫了一個(gè)包含文本和按鈕的頁(yè)面。為了幫助開發(fā)者熟悉在代碼中創(chuàng)建布局的方式,接下來(lái)我們使用代碼的方式編寫第二個(gè)頁(yè)面。
在“Project”窗口,打開“entry > src > main > java > com.example.myapplication”,右鍵點(diǎn)擊“slice”文件夾,選擇“New > Java Class”,命名為“SecondAbilitySlice”,單擊回車鍵。第二個(gè)頁(yè)面上有一個(gè)文本。在上一步創(chuàng)建的“SecondAbilitySlice”文件中,添加一個(gè)Text,示例代碼如下:
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DependentLayout.LayoutConfig;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
public class SecondAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// 聲明布局
DependentLayout myLayout = new DependentLayout(this);
// 設(shè)置布局寬高
myLayout.setWidth(LayoutConfig.MATCH_PARENT);
myLayout.setHeight(LayoutConfig.MATCH_PARENT);
// 設(shè)置布局背景為白色
ShapeElement background = new ShapeElement();
background.setRgbColor(new RgbColor(255, 255, 255));
myLayout.setBackground(background);
// 創(chuàng)建一個(gè)文本
Text text = new Text(this);
text.setText("Hi there");
text.setWidth(LayoutConfig.MATCH_PARENT);
text.setTextSize(100);
text.setTextColor(Color.BLACK);
// 設(shè)置文本的布局
DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
textConfig.addRule(LayoutConfig.CENTER_IN_PARENT);
text.setLayoutConfig(textConfig);
myLayout.addComponent(text);
super.setUIContent(myLayout);
}
}
往期推薦
評(píng)論
圖片
表情
