目錄:
鴻蒙應用開發入門(一):鴻蒙系統的概述
鴻蒙應用開發入門(二):開發環境搭建
鴻蒙應用開發入門(三):開發第一個鴻蒙應用
鴻蒙應用開發入門(四):進一步了解第一個例子里的細節
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
