《鸿蒙开发 3 天速成:核心知识点 + 实战案例精讲》

0 阅读8分钟

速成学习的核心原则

为什么3天可以入门鸿蒙开发?

鸿蒙开发采用声明式UI和简化的开发模型,大大降低了学习门槛。通过聚焦核心知识点和实战练习,3天时间足以掌握基础开发能力,能够开发简单的鸿蒙应用。

速成学习三原则

  1. 聚焦核心:只学习最常用的20%知识点,解决80%的问题
  2. 实战导向:每个知识点都配合实战案例,强化应用能力
  3. 高频回顾:每天开始前回顾前一天内容,强化记忆

学习时间安排

  • 每天建议学习时间:4-6小时(可拆分为上午和下午)
  • 每学习45分钟,休息10分钟,保持高效学习状态
  • 晚上安排30分钟回顾当天内容,巩固学习效果

准备工作

  • 安装DevEco Studio开发环境(提前1天准备)
  • 准备一个简单的记事本,记录学习要点和问题
  • 确保网络畅通,便于查阅文档和资源

第一天:鸿蒙开发基础

上午:开发环境搭建与基础语法

开发环境搭建(2小时)

  1. 安装DevEco Studio

    • 访问华为开发者官网下载最新版DevEco Studio
    • 运行安装程序,使用默认设置完成安装
    • 首次启动时选择"HarmonyOS开发"
    • 安装HarmonyOS SDK(选择最新稳定版)
  2. 配置开发环境

    • 配置Node.js环境(DevEco Studio会自动安装)
    • 配置模拟器(推荐选择P50 Pro机型)
    • 熟悉DevEco Studio界面布局和常用功能
  3. 创建第一个应用

    • 点击"Create Project",选择"Empty Ability"模板
    • 填写项目信息(Project Name: MyFirstApp)
    • 等待项目创建完成(首次创建较慢,需耐心等待)
    • 运行默认应用,验证环境是否配置成功

ArkTS基础语法(2小时)

  1. 变量与数据类型

    • 基本数据类型:number、string、boolean、array、object
    • 变量声明:let(可变)和const(不可变)
    • 类型注解:显式指定变量类型
    // 变量定义示例
    let count: number = 10;
    const message: string = "Hello HarmonyOS";
    let isReady: boolean = true;
    let numbers: number[] = [1, 2, 3, 4, 5];
    let user: { name: string, age: number } = { name: "Alice", age: 25 };
    

  2. 函数定义与调用

    • 函数声明和参数类型注解
    • 返回值类型注解
    • 函数调用和参数传递
    // 函数定义示例
    function add(a: number, b: number): number {
      return a + b;
    }
    
    function greet(name: string): string {
      return `Hello, ${name}!`;
    }
    
    // 函数调用
    let result = add(3, 5);
    let greeting = greet("HarmonyOS");
    

  3. 控制流语句

    • 条件语句:if-else
    • 循环语句:for、while
    • 分支语句:switch-case
    // 控制流示例
    let score: number = 85;
    
    if (score >= 90) {
      console.log("优秀");
    } else if (score >= 60) {
      console.log("及格");
    } else {
      console.log("不及格");
    }
    
    // 循环示例
    for (let i = 0; i < 5; i++) {
      console.log(`循环第 ${i} 次`);
    }
    

下午:核心概念与第一个应用

鸿蒙核心概念(2小时)

  1. 应用结构

    • 项目目录结构解析
    • 配置文件作用
    • 资源管理方式
  2. Ability概念

    • Ability作为应用基本单元
    • Page Ability(带UI界面)
    • Service Ability(后台服务)
  3. 声明式UI思想

    • 声明式vs命令式UI开发
    • UI描述与逻辑分离
    • 状态驱动UI更新

实战案例:个人名片应用(2小时)

  1. 项目创建与准备

    • 创建新的Empty Ability项目
    • 熟悉项目结构和配置文件
    • 准备所需资源(图片等)
  2. 界面布局实现

    • 使用Column和Row布局容器
    • 添加Text组件显示个人信息
    • 使用Image组件显示头像
    • 设置适当的边距和间距
    @Entry
    @Component
    struct Index {
      build() {
        Column() {
          // 头像
          Image($r('app.media.profile'))
            .width(120)
            .height(120)
            .borderRadius(60)
            .margin(20)
            
          // 姓名
          Text('张三')
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .margin(5)
            
          // 职位
          Text('鸿蒙开发工程师')
            .fontSize(16)
            .fontColor('#666666')
            .margin(5)
            
          // 联系方式
          Column() {
            Text('电话:13800138000')
            Text('邮箱:zhangsan@example.com')
            Text('地址:北京市海淀区')
          }
          .fontSize(14)
          .spacing(8)
          .margin(15)
        }
        .width('100%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
        .backgroundColor('#F5F5F5')
      }
    }
    

  3. 样式美化

    • 设置背景颜色
    • 添加边框和圆角
    • 调整字体大小和颜色
  4. 运行与调试

    • 在模拟器中运行应用
    • 调试布局问题
    • 优化界面细节

第二天:UI开发与交互

上午:常用组件与布局

常用UI组件(2小时)

  1. 基础组件

    • Text:文本显示
    • Button:按钮交互
    • Image:图片显示
    • TextInput:文本输入
    • List:列表展示
    // 常用组件示例
    Column() {
      Text('这是文本组件')
        .fontSize(18)
        .margin(5)
        
      Button('点击我')
        .width(120)
        .height(40)
        .backgroundColor('#007DFF')
        .margin(5)
        .onClick(() => {
          console.log('按钮被点击');
        })
        
      Image($r('app.media.icon'))
        .width(80)
        .height(80)
        .margin(5)
        
      TextInput({ placeholder: '请输入文本' })
        .width('80%')
        .height(40)
        .backgroundColor('#FFFFFF')
        .padding(10)
        .margin(5)
    }
    .padding(10)
    

  2. 容器组件

    • Column:垂直布局
    • Row:水平布局
    • Flex:弹性布局
    • Stack:层叠布局
    • List:列表布局
  3. 组件属性设置

    • 尺寸设置(width、height)
    • 边距设置(margin、padding)
    • 背景设置(backgroundColor)
    • 边框设置(border、borderRadius)

布局技巧(2小时)

  1. 弹性布局

    • 使用Flex实现自适应布局
    • 权重分配(flexGrow)
    • 对齐方式设置
    Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
      Text('左侧')
      Text('中间')
      Text('右侧')
    }
    .width('100%')
    .height(50)
    .backgroundColor('#EEEEEE')
    .padding(10)
    

  2. 响应式布局

    • 使用百分比设置尺寸
    • 媒体查询适配不同屏幕
    • 断点系统应用
  3. 布局优化

    • 减少布局嵌套
    • 避免过度约束
    • 合理使用空白空间

实战案例:登录界面(2小时)

  1. 界面结构设计

    • 标题区域
    • 输入区域(用户名、密码)
    • 按钮区域(登录按钮)
    • 辅助区域(忘记密码、注册)
  2. 布局实现

    • 使用Column垂直排列元素
    • 使用Flex实现输入框布局
    • 设置适当的间距和边距
  3. 样式美化

    • 添加背景和边框
    • 设置输入框样式
    • 美化按钮样式

下午:状态管理与交互

状态管理基础(2小时)

  1. @State装饰器

    • 组件内部状态管理
    • 状态变化触发UI更新
    • 简单状态声明和使用
    @Entry
    @Component
    struct CounterComponent {
      @State count: number = 0
      
      build() {
        Column() {
          Text(`Count: ${this.count}`)
            .fontSize(24)
            .margin(10)
          
          Row({ space: 10 }) {
            Button('-')
              .onClick(() => this.count--)
            
            Button('+')
              .onClick(() => this.count++)
          }
        }
        .width('100%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
      }
    }
    

  2. 事件处理

    • 点击事件(onClick)
    • 输入事件(onChange)
    • 触摸事件(onTouch)
    • 手势识别(Gesture)
  3. 数据绑定

    • 单向绑定
    • 双向绑定
    • 状态传递

实战案例:计数器应用(2小时)

  1. *功能设计

    • 显示计数值
    • 加减按钮控制计数
    • 重置按钮归零
    • 计数范围限制(0-100)
  2. 状态管理实现

    • 使用@State管理计数值
    • 实现加减和重置方法
    • 添加计数范围限制逻辑
  3. UI界面实现

    • 设计计数器布局
    • 添加按钮交互效果
    • 美化界面样式
  4. 功能扩展

    • 添加步进值设置
    • 实现计数历史记录
    • 添加动画效果

第三天:实战项目开发

上午:数据存储与网络请求

数据存储基础(2小时)

  1. Preferences存储

    • 轻量级键值对存储
    • 数据保存与读取
    • 应用配置存储
    import preferences from '@ohos.data.preferences';
    
    class PreferenceUtil {
      private pref: preferences.Preferences | null = null;
      
      // 初始化
      async init(context: Context) {
        try {
          this.pref = await preferences.getPreferences(context, 'app_prefs');
        } catch (error) {
          console.error('初始化Preferences失败', error);
        }
      }
      
      // 保存数据
      async saveData(key: string, value: preferences.ValueType): Promise<boolean> {
        if (!this.pref) return false;
        
        try {
          await this.pref.put(key, value);
          await this.pref.flush();
          return true;
        } catch (error) {
          console.error(`保存数据失败: ${key}`, error);
          return false;
        }
      }
      
      // 获取数据
      async getData(key: string, defaultValue: preferences.ValueType): Promise<preferences.ValueType> {
        if (!this.pref) return defaultValue;
        
        try {
          return await this.pref.get(key, defaultValue);
        } catch (error) {
          console.error(`获取数据失败: ${key}`, error);
          return defaultValue;
        }
      }
    }
    

  2. 文件存储

    • 文件创建与读写
    • 目录结构与访问权限
    • 二进制数据存储

网络请求(2小时)

  1. HTTP请求基础

    • GET请求获取数据
    • POST请求提交数据
    • 请求头设置
    • 响应处理
    import http from '@ohos.net.http';
    
    class HttpUtil {
      // GET请求
      async get(url: string): Promise<any> {
        let request = http.createHttp();
        
        try {
          let response = await request.request(
            url,
            {
              method: http.RequestMethod.GET,
              header: {
                'Content-Type': 'application/json'
              },
              connectTimeout: 60000,
              readTimeout: 60000
            }
          );
          
          if (response.responseCode === 200) {
            return JSON.parse(response.result as string);
          } else {
            console.error(`HTTP请求失败: ${response.responseCode}`);
            return null;
          }
        } catch (error) {
          console.error('网络请求异常', error);
          return null;
        } finally {
          request.destroy();
        }
      }
    }
    

  2. JSON数据解析

    • JSON字符串与对象转换
    • 数据模型定义
    • 复杂JSON解析

下午:综合实战项目

实战项目:待办事项应用(4小时)

  1. 项目规划与设计

    • 功能需求分析
    • 界面设计
    • 数据模型定义
  2. 项目结构搭建

    • 创建新项目
    • 组织目录结构
    • 准备资源文件
  3. 核心功能实现

    数据模型定义

    // 待办事项数据模型
    export interface TodoItem {
      id: string;          // 唯一ID
      content: string;     // 待办内容
      completed: boolean;  // 是否完成
      createTime: number;  // 创建时间戳
    }
    

    数据服务实现

    // 待办事项服务
    import { TodoItem } from '../model/TodoModel';
    import preferences from '@ohos.data.preferences';
    
    export class TodoService {
      private pref: preferences.Preferences | null = null;
      private readonly TODO_KEY = 'todo_list';
      
      async init(context: Context) {
        this.pref = await preferences.getPreferences(context, 'todo_prefs');
      }
      
      // 获取所有待办事项
      async getTodos(): Promise<TodoItem[]> {
        if (!this.pref) return [];
        
        const value = await this.pref.get(this.TODO_KEY, '[]');
        return JSON.parse(value as string) as TodoItem[];
      }
      
      // 添加待办事项
      async addTodo(content: string): Promise<boolean> {
        if (!this.pref || !content.trim()) return false;
        
        const todos = await this.getTodos();
        const newTodo: TodoItem = {
          id: Date.now().toString(),
          content: content.trim(),
          completed: false,
          createTime: Date.now()
        };
        
        todos.unshift(newTodo);
        return this.saveTodos(todos);
      }
      
      // 标记待办事项完成状态
      async toggleTodo(id: string): Promise<boolean> {
        if (!this.pref) return false;
        
        const todos = await this.getTodos();
        const index = todos.findIndex(item => item.id === id);
        
        if (index === -1) return false;
        
        todos[index].completed = !todos[index].completed;
        return this.saveTodos(todos);
      }
      
      // 删除待办事项
      async deleteTodo(id: string): Promise<boolean> {
        if (!this.pref) return false;
        
        let todos = await this.getTodos();
        todos = todos.filter(item => item.id !== id);
        
        return this.saveTodos(todos);
      }
      
      // 保存待办事项列表
      private async saveTodos(todos: TodoItem[]): Promise<boolean> {
        try {
          await this.pref!.put(this.TODO_KEY, JSON.stringify(todos));
          await this.pref!.flush();
          return true; } catch (error) {
          console.error('保存待办事项失败', error);
          return false;
        }
      }
    }
    

    主页面实现

    @Entry
    @Component
    struct TodoApp {
      @State todos: TodoItem[] = [];
      @State newTodo: string = '';
      private todoService: TodoService = new TodoService();
      
      async aboutToAppear() {
        await this.todoService.init(getContext(this));
        this.todos = await this.todoService.getTodos();
      }
      
      build() {
        Column() {
          Text('待办事项')
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .margin({ top: 30, bottom: 20 })
            .alignSelf(FlexAlign.Start)
          
          // 输入区域
          Row() {
            TextInput({ placeholder: '添加新的待办事项...' })
              .flexGrow(1)
              .height(40)
              .padding(10)
              .backgroundColor('#FFFFFF')
              .borderRadius(8)
              .onChange((value) => this.newTodo = value)
              .onSubmit(() => this.addTodo())
            
            Button('添加')
              .width(80)
              .height(40)
              .margin({ left: 10 })
              .backgroundColor('#007DFF')
              .onClick(() => this.addTodo())
          }
          
          // 待办事项列表
          if (this.todos.length === 0) {
            Text('暂无待办事项')
              .fontSize(16)
              .color('#888888')
              .margin(20)
          } else {
            List({ space: 10 }) {
              ForEach(this.todos, (item) => {
                ListItem() {
                  Row() {
                    Checkbox()
                      .checked(item.completed)
                      .onChange((checked) => this.toggleTodo(item.id))
                      .width(24)
                      .height(24)
                      .margin({ right: 10 })
                    
                    Text(item.content)
                      .flexGrow(1)
                      .fontSize(16)
                      .decoration({
                        type: item.completed ? TextDecorationType.LineThrough : TextDecorationType.None,
                        color: '#888888'
                      })
                      .fontColor(item.completed ? '#888888' : '#333333')
                    
                    Button('删除')
                      .fontSize(12)
                      .width(60)
                      .height(30)
                      .backgroundColor('#FF4D4F')
                      .onClick(() => this.deleteTodo(item.id))
                  }
                  .width('100%')
                  .padding(10)
                  .backgroundColor('#FFFFFF')
                  .borderRadius(8)
                }
              }, (item) => item.id)
            }
            .layoutWeight(1)
            .margin({ top: 10 })
          }
        }
        .width('100%')
        .height('100%')
        .padding(16)
        .backgroundColor('#F5F5F5')
      }
      
      async addTodo() {
        if (this.newTodo.trim()) {
          await this.todoService.addTodo(this.newTodo);
          this.todos = await this.todoService.getTodos();
          this.newTodo = '';
        }
      }
      
      async toggleTodo(id: string) {
        await this.todoService.toggleTodo(id);
        this.todos = await this.todoService.getTodos();
      }
      
      async deleteTodo(id: string) {
        await this.todoService.deleteTodo(id);
        this.todos = await this.todoService.getTodos();
      }
    }
    

  4. 功能测试与优化

    • 测试所有功能点
    • 优化界面布局和交互
    • 修复发现的问题

结语:3天后的学习路径

速成之后的进阶方向

3天速成的局限性

本指南专注于快速入门鸿蒙开发,覆盖了基础UI开发、简单状态管理和数据存储,但鸿蒙开发还有更多高级特性需要深入学习,如分布式能力、动画效果、性能优化等。

进阶学习路径

  1. 基础巩固

    • 深入学习ArkTS语言特性
    • 掌握更多UI组件和布局方式
    • 熟练使用状态管理
  2. 中级技能

    • 分布式应用开发
    • 动画与交互动效
    • 多线程编程
    • 网络请求深入
  3. 高级技能

    • 应用架构设计
    • 性能优化
    • 测试与调试
    • 应用发布上架

推荐学习资源

码牛教育官方的动态 - 哔哩哔哩

实战建议

  • 继续完善待办事项应用,添加更多功能
  • 尝试开发其他类型应用,如天气应用、新闻应用
  • 参与开源项目,积累实战经验
  • 加入学习社群,与其他开发者交流

通过3天的速成学习,你已经具备了鸿蒙开发的基础能力。但编程学习是一个持续的过程,建议每天保持学习习惯,不断实践和探索,逐步提升开发技能。祝你在鸿蒙开发之路上取得更大进步!