鴻蒙開發入門教程
一、技術簡介
鴻蒙操作系統(HarmonyOS)是面向萬物互聯時代的全場景分布式操作系統,具備分布式軟總線、分布式數據管理、分布式任務調度等核心能力,能讓設備間實現無縫連接與協同,為用戶提供統一、流暢的交互體驗。
開發語言方面,ArkTS 是專門為鴻蒙開發設計的語言,結合了 TypeScript 的類型系統與聲明式編程范式,提升了開發效率和代碼的可維護性。值得一提的是功能寫法也和前端VUE框架頗為相似,相信在我國具有大基數的前端開發者會很容易上手吧
二、工具安裝
- 下載 DevEco Studio
訪問 華為開發者官網,在官網找到 DevEco Studio 的下載鏈接,依據自身操作系統(Windows、Mac 或 Linux)選擇合適版本下載。 - 安裝 DevEco Studio
運行下載好的安裝程序,按照提示完成安裝。安裝過程中可按需選擇安裝路徑和組件。 - 配置 SDK
打開 DevEco Studio,選擇 “Tools” -> “SDK Manager”,在 “SDK Platforms” 中選擇所需的鴻蒙 SDK 版本進行下載安裝;在 “SDK Tools” 中安裝必要工具,如 Build Tools、Platform - Tools 等。 - 創建項目
打開 DevEco Studio,點擊 “File” -> “New” -> “New Project”,選擇基于 ArkTS 的項目模板(如 “Empty Ability (ArkTS)”),點擊 “Next”,配置項目信息(項目名稱、保存位置、包名等),最后點擊 “Finish” 完成項目創建。
三、核心單元介紹
- Ability
Ability 是鴻蒙應用的基本功能單元,負責處理應用的各種能力和業務邏輯。分為 FA(Feature Ability)和 PA(Particle Ability)。
FA(Feature Ability)
用于實現具有用戶界面的功能,類似于 Android 中的 Activity。通常用于展示界面、與用戶交互等。
// 在 pages 目錄下創建 Index.ets 文件
@Entry
@Component
struct Index {build() {Column({ space: 50 }) {Text('This is a Feature Ability page.').fontSize(30).width('100%').textAlign(TextAlign.Center)}.width('100%')}
}
PA(Particle Ability)
用于實現無用戶界面的功能,如后臺服務、數據處理等,類似于 Android 中的 Service。
// 在 service 目錄下創建 MyService.ets 文件
@Service
@Component
struct MyService {onStart() {console.log('MyService started.')// 在這里可以執行后臺任務,如數據同步、定時任務等}onStop() {console.log('MyService stopped.')}
}
2. Module
Module 是對 Ability 的進一步封裝,包含多個 Ability 以及相關的資源和配置信息,便于對應用功能進行模塊化管理。在 config.json
中可以對 Module 進行配置,例如指定 Module 的名稱、包含的 Ability 等。
{"module": {"name": "entry","reqPermissions": [{"name": "ohos.permission.INTERNET","reason": "Need internet access to fetch data","usedScene": {"ability": ["com.example.myapp.MainAbility"],"when": "always"}}],"abilities": [{"name": "com.example.myapp.MainAbility","icon": "$media:icon","label": "$string:mainability_label","srcEntrance": "pages/Index.ets","description": "$string:mainability_description","type": "page","launchType": "standard"},{"name": "com.example.myapp.MyService","srcEntrance": "service/MyService.ets","description": "$string:myservice_description","type": "service"}]}
}
四、重要 UI 組件
- Text
用于顯示文本內容。
@Entry
@Component
struct Index {build() {Text('Hello, HarmonyOS!').fontSize(30).fontWeight(FontWeight.Bold).textAlign(TextAlign.Center)}
}
2. Button
用于觸發操作。
@Entry
@Component
struct Index {@State clickCount: number = 0build() {Column({ space: 50 }) {Text(`Button clicked ${this.clickCount} times.`).fontSize(20).width('100%').textAlign(TextAlign.Center)Button('Click me').onClick(() => {this.clickCount++}).width('50%').margin({ left: '25%' })}.width('100%')}
}
3. Image
用于顯示圖片。
@Entry
@Component
struct Index {build() {Image($r('app.media.sample_image')).width(200).height(200).objectFit(ImageFit.Contain).margin({ top: 100 }).width('100%').imageAlign(ImageAlign.Center)}
}
4. Column 和 Row
用于布局組件,Column
實現垂直布局,Row
實現水平布局。
@Entry
@Component
struct Index {build() {Column({ space: 20 }) {Text('Vertical Item 1')Text('Vertical Item 2')Row({ space: 20 }) {Text('Horizontal Item 1')Text('Horizontal Item 2')}}.width('100%')}
}
五、常用功能
1. 條件渲染
根據條件決定是否渲染組件。
@Entry
@Component
struct Index {@State showText: boolean = falsebuild() {Column({ space: 50 }) {Button(this.showText? 'Hide Text' : 'Show Text').onClick(() => {this.showText =!this.showText}).width('50%').margin({ left: '25%' })if (this.showText) {Text('This text is conditionally rendered.').fontSize(20).width('100%').textAlign(TextAlign.Center)}}.width('100%')}
}
2. 列表渲染
使用 ForEach
組件渲染列表數據。
@Entry
@Component
struct Index {private fruits: string[] = ['Apple', 'Banana', 'Cherry']build() {Column({ space: 20 }) {ForEach(this.fruits, (fruit) => {Text(fruit).fontSize(20).width('100%').textAlign(TextAlign.Center)}, (fruit) => fruit)}.width('100%')}
}
3. 頁面導航
在不同頁面間進行導航。
// 在 pages 目錄下創建 SecondPage.ets 文件
@Component
struct SecondPage {build() {Column({ space: 50 }) {Text('This is the second page.').fontSize(30).width('100%').textAlign(TextAlign.Center)Button('Go back to first page').onClick(() => {router.back()}).width('50%').margin({ left: '25%' })}.width('100%')}
}// 在 Index.ets 中添加導航按鈕
@Entry
@Component
struct Index {build() {Column({ space: 50 }) {Text('This is the first page.').fontSize(30).width('100%').textAlign(TextAlign.Center)Button('Go to second page').onClick(() => {router.pushUrl({ url: 'pages/SecondPage' })}).width('50%').margin({ left: '25%' })}.width('100%')}
}
六、常用函數
1. onClick
用于綁定按鈕等組件的點擊事件。
@Entry
@Component
struct Index {@State message: string = 'Button not clicked'build() {Button('Click me').onClick(() => {this.message = 'Button clicked!'})Text(this.message).fontSize(20).width('100%').textAlign(TextAlign.Center)}
}
2. onChange
用于綁定輸入框等組件的值變化事件。
@Entry
@Component
struct Index {@State inputValue: string = ''build() {Column({ space: 20 }) {Input({ placeholder: 'Enter text' }).onChange((value: string) => {this.inputValue = value})Text(`You entered: ${this.inputValue}`).fontSize(20).width('100%').textAlign(TextAlign.Center)}.width('100%')}
}
3. router.pushUrl 和 router.back
用于頁面導航,router.pushUrl
用于跳轉到指定頁面,router.back
用于返回上一頁,如前面頁面導航示例所示。