鴻蒙應用開發入門(三):開發第一個鴻蒙應用
阿新 • • 發佈:2020-12-22
目錄:
鴻蒙應用開發入門(一):鴻蒙系統的概述
鴻蒙應用開發入門(二):開發環境搭建
鴻蒙應用開發入門(三):開發第一個鴻蒙應用
鴻蒙應用開發入門(四):進一步瞭解第一個例子裡的細節
3.1 第一個鴻蒙應用實現需求
編寫兩張頁面,實現在第一張頁面點選按鈕跳轉到第二張頁面。在Java UI框架中,提供了兩種編寫佈局的方式:在XML中宣告UI佈局和在程式碼中建立佈局。這兩種方式創建出的佈局沒有本質差別,都是我們需要熟悉方式,所以我們將通過XML的方式佈局第一張頁面,然後再通過程式碼的方式佈局第二張頁面。
3.2 用XML佈局第一張頁面
1. 開啟layout下面的“ability_main.xml”檔案 2. 在“ability_main.xml”檔案中建立一個文字和一個按鈕
<?xml version="1.0" encoding="utf-8"?> <DependentLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:width="match_parent" ohos:height="match_parent" ohos:background_element="#000000"> <Text ohos:id="$+id:text" ohos:width="match_content" ohos:height="match_content" ohos:text="Hello World" ohos:text_color="white" ohos:text_size="32fp" ohos:center_in_parent="true"/> <Button ohos:id="$+id:button" ohos:width="match_content" ohos:height="match_content" ohos:text="Next" ohos:text_size="19fp" ohos:text_color="white" ohos:top_padding="8vp" ohos:bottom_padding="8vp" ohos:right_padding="80vp" ohos:left_padding="80vp" ohos:background_element="$graphic:background_button" ohos:below="$id:text" ohos:horizontal_center="true" /> </DependentLayout>
3. 建立按鈕的背景
按鈕的背景是通過“background_button”來指定的。右鍵點選“graphic”資料夾,選擇“New > File”,命名為“background_button.xml”。
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="oval"> <solid ohos:color="#007DFF"/> <corners ohos:radius="20"/> </shape>
3.3 用程式設計的方式佈局第二張頁面
1. 建立Feature Ability
2. 程式碼編寫介面
public class SecondAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// 宣告佈局
DependentLayout myLayout = new DependentLayout(this);
// 設定頁面佈局大小和背景色
myLayout.setWidth(MATCH_PARENT);
myLayout.setHeight(MATCH_PARENT);
ShapeElement element = new ShapeElement();
element.setRgbColor(new RgbColor(255, 255, 255));
myLayout.setBackground(element);
// 建立一個文字
Text text = new Text(this);
text.setText("Nice to meet you.");
text.setTextSize(55);
text.setTextColor(Color.BLACK);
// 設定文字的佈局
DependentLayout.LayoutConfig textConfig =
new DependentLayout.LayoutConfig(MATCH_CONTENT,MATCH_CONTENT);
textConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
text.setLayoutConfig(textConfig);
myLayout.addComponent(text);
super.setUIContent(myLayout);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
作者:zhonghongfa
想了解更多內容,請訪問: 51CTO和華為官方戰略合作共建的鴻蒙技術社群https://harmonyos.51cto.com