一、Image 图片组件

1.1 组件参数

参数类型

用途

用法

注意事项

string

路径引用图片(本地+网络)

本地:Image('images/icon.png') 网络:Image('https://example.com/img.jpg')

本地图片必须放在ets目录下,使用相对路径; 真机加载网络图片需配置网络权限,预览器/模拟器无需

Resource

引用resources目录下资源

media目录:Image($r('app.media.image')) rawfile目录:Image($rawFile('icon.png'))

media引用不带后缀,rawfile引用必须带后缀; 系统自动匹配多语言/多设备版本,无匹配时使用base版本

PixelMap

像素位图(图片编辑)

Image(pixelMapObject)

用于图片裁剪、滤镜等编辑场景,普通显示无需使用

1.2 常用属性

1.2.1 尺寸属性(width/height)

  • 参数类型:string | number | Resource

  • 单位说明:

    • PX:物理像素,不同密度屏幕显示大小不同

    • VP:虚拟像素(推荐),自动适配屏幕密度,1VP = PPI/160 PX

    • 纯数字默认单位为VP

1.2.2 缩放属性(objectFit)

  • 参数:ImageFit枚举类型

  • 可选值:None(不缩放)| Contain(完整显示)| Cover(填满裁剪)| Fill(拉伸填满)| ScaleDown(仅缩小)| Auto(自动)

1.2.3 插值属性(interpolation)

  • 用途:低分辨率图片放大时抗锯齿

  • 参数:ImageInterpolation枚举类型

  • 可选值:None | Low | Medium | High(质量越高,渲染越慢)

1.3 Image组件完整代码示例

// ImageDemo.ets
@Entry
@Component
struct ImageDemo {
  build() {
    Column({ space: 20 }) {
      // 1. string类型:本地图片(ets目录下)
      Image('images/local.png')
        .width(100)
        .height(100)

      // 2. string类型:网络图片
      Image('https://picsum.photos/200/200')
        .width(100)
        .height(100)

      // 3. Resource类型:media目录
      Image($r('app.media.phone'))
        .width(100)
        .height(100)

      // 4. Resource类型:rawfile目录
      Image($rawFile('icon.png'))
        .width(100)
        .height(100)

      // 5. 不同缩放效果对比
      Row({ space: 10 }) {
        Image($r('app.media.phone'))
          .width(80)
          .height(80)
          .objectFit(ImageFit.Contain)
          .border({ width: 1, color: Color.Gray })

        Image($r('app.media.phone'))
          .width(80)
          .height(80)
          .objectFit(ImageFit.Cover)
          .border({ width: 1, color: Color.Gray })

        Image($r('app.media.phone'))
          .width(80)
          .height(80)
          .objectFit(ImageFit.Fill)
          .border({ width: 1, color: Color.Gray })
      }

      // 6. 插值效果(低分辨率图片放大)
      Image($r('app.media.small_icon')) // 32x32小图
        .width(200)
        .height(200)
        .interpolation(ImageInterpolation.High)
    }
    .padding(20)
    .width('100%')
  }
}

二、Text 文本组件

2.1 组件参数

参数类型

用途

用法

string

直接显示文本

Text('你好,鸿蒙')

Resource

引用多语言文本

Text($r('app.string.greeting'))

2.2 常用属性

属性

说明

示例

fontSize

字体大小,单位FP(推荐),纯数字默认FP

.fontSize(24)

fontWeight

字体粗细,支持数字(100-900)、枚举、字符串

.fontWeight(FontWeight.Bold)

fontColor

字体颜色,支持枚举、RGB、十六进制

.fontColor('#FF0000')

textAlign

文本对齐,Start/Center/End

.textAlign(TextAlign.Center)

maxLines

最大显示行数

.maxLines(2)

textOverflow

超长处理,Clip(截断)/Ellipsis(省略号)

.textOverflow({ overflow: TextOverflow.Ellipsis })

2.3 Text组件完整代码示例

// TextDemo.ets
@Entry
@Component
struct TextDemo {
  build() {
    Column({ space: 20 }) {
      // 1. 基础文本
      Text('基础文本')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .fontColor('#333333')

      // 2. 多语言文本
      Text($r('app.string.greeting'))
        .fontSize(18)

      // 3. 不同字体粗细
      Row({ space: 10 }) {
        Text('细体').fontWeight(100)
        Text('常规').fontWeight(400)
        Text('粗体').fontWeight(700)
        Text('加粗').fontWeight(FontWeight.Bolder)
      }

      // 4. 文本对齐
      Column({ space: 5 }) {
        Text('左对齐').textAlign(TextAlign.Start).width('100%').backgroundColor('#F5F5F5')
        Text('居中对齐').textAlign(TextAlign.Center).width('100%').backgroundColor('#F5F5F5')
        Text('右对齐').textAlign(TextAlign.End).width('100%').backgroundColor('#F5F5F5')
      }
      .width('100%')

      // 5. 超长处理
      Text('这是一段很长很长的文本,超过两行后会显示省略号,这是一段很长很长的文本,超过两行后会显示省略号')
        .maxLines(2)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .width(200)
        .backgroundColor('#F5F5F5')
        .padding(5)
    }
    .padding(20)
    .width('100%')
  }
}// TextDemo.ets
@Entry
@Component
struct TextDemo {
  build() {
    Column({ space: 20 }) {
      // 1. 基础文本
      Text('基础文本')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .fontColor('#333333')

      // 2. 多语言文本
      Text($r('app.string.greeting'))
        .fontSize(18)

      // 3. 不同字体粗细
      Row({ space: 10 }) {
        Text('细体').fontWeight(100)
        Text('常规').fontWeight(400)
        Text('粗体').fontWeight(700)
        Text('加粗').fontWeight(FontWeight.Bolder)
      }

      // 4. 文本对齐
      Column({ space: 5 }) {
        Text('左对齐').textAlign(TextAlign.Start).width('100%').backgroundColor('#F5F5F5')
        Text('居中对齐').textAlign(TextAlign.Center).width('100%').backgroundColor('#F5F5F5')
        Text('右对齐').textAlign(TextAlign.End).width('100%').backgroundColor('#F5F5F5')
      }
      .width('100%')

      // 5. 超长处理
      Text('这是一段很长很长的文本,超过两行后会显示省略号,这是一段很长很长的文本,超过两行后会显示省略号')
        .maxLines(2)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .width(200)
        .backgroundColor('#F5F5F5')
        .padding(5)
    }
    .padding(20)
    .width('100%')
  }
}

三、Button 按钮组件

3.1 组件参数

3.1.1 无嵌套子组件

Button(label: string, options?: { type?: ButtonType, stateEffect?: boolean })
  • label:按钮显示文字

  • options.type:按钮形状,Capsule(胶囊,默认)| Circle(圆形)| Normal(方形)

  • options.stateEffect:是否开启点击效果,默认true

3.1.2 嵌套子组件

Button(options?: { type?: ButtonType, stateEffect?: boolean }) {
  // 子组件:Image、Text、Row等
}

3.2 常用属性与事件

  • 常用属性:backgroundColorborderRadiuswidthheightfontSize

  • 常用事件:onClick(() => void)(点击事件)

3.3 Button组件完整代码示例

// ButtonDemo.ets
@Entry
@Component
struct ButtonDemo {
  build() {
    Column({ space: 20 }) {
      // 1. 基础胶囊按钮
      Button('胶囊按钮')
        .onClick(() => {
          console.log('胶囊按钮被点击')
        })

      // 2. 圆形按钮
      Button('圆', { type: ButtonType.Circle })
        .width(60)
        .height(60)
        .fontSize(14)

      // 3. 方形按钮+圆角
      Button('方形按钮', { type: ButtonType.Normal })
        .borderRadius(10)
        .backgroundColor('#007DFF')

      // 4. 关闭点击效果
      Button('无点击效果', { stateEffect: false })
        .backgroundColor('#FF5722')

      // 5. 自定义按钮(图标+文字)
      Button({ type: ButtonType.Capsule }) {
        Row({ space: 5 }) {
          Image($r('app.media.search'))
            .width(20)
            .height(20)
          Text('搜索')
            .fontSize(16)
            .fontColor(Color.White)
        }
      }
      .backgroundColor('#007DFF')
      .onClick(() => {
        console.log('搜索按钮被点击')
      })
    }
    .padding(20)
    .width('100%')
  }
}

四、Toggle 切换按钮组件

4.1 组件参数

Toggle(options: { type: ToggleType, isOn?: boolean })
  • type:组件类型,Switch(开关)| Checkbox(复选框)| Button(按钮)

  • isOn:初始状态,true开启/选中,false关闭/未选中

4.2 常用属性与事件

  • 常用属性:selectedColor(选中背景色)、switchThumbColor(Switch滑块颜色)

  • 常用事件:onChange((isOn: boolean) => void)(状态变化事件)

4.3 Toggle组件完整代码示例

// ToggleDemo.ets
@Entry
@Component
struct ToggleDemo {
  @State isLightOn: boolean = false

  build() {
    Column({ space: 30 }) {
      // 1. 开关类型
      Row({ space: 10 }) {
        Text('蓝牙开关:')
        Toggle({ type: ToggleType.Switch, isOn: true })
          .selectedColor('#007DFF')
          .switchThumbColor(Color.White)
          .onChange((isOn) => {
            console.log(`蓝牙状态:${isOn ? '开启' : '关闭'}`)
          })
      }

      // 2. 复选框类型
      Row({ space: 10 }) {
        Text('同意协议:')
        Toggle({ type: ToggleType.Checkbox, isOn: false })
          .selectedColor('#007DFF')
          .onChange((isOn) => {
            console.log(`协议同意:${isOn}`)
          })
      }

      // 3. 按钮类型
      Toggle({ type: ToggleType.Button, isOn: this.isLightOn }) {
        Text(this.isLightOn ? '开灯' : '关灯')
          .fontColor(Color.White)
      }
      .width(100)
      .height(40)
      .selectedColor('#FF9800')
      .onChange((isOn) => {
        this.isLightOn = isOn
        console.log(`灯状态:${isOn ? '开' : '关'}`)
      })

      // 4. 实际应用:控制图片显示
      Column({ space: 10 }) {
        Toggle({ type: ToggleType.Switch, isOn: this.isLightOn })
          .onChange((isOn) => {
            this.isLightOn = isOn
          })
        Image(this.isLightOn ? $r('app.media.light_on') : $r('app.media.light_off'))
          .width(100)
          .height(100)
      }
    }
    .padding(20)
    .width('100%')
  }
}

五、TextInput 文本输入组件

5.1 组件参数

TextInput(value?: { placeholder?: string, text?: string })
  • placeholder:提示文本(无输入时显示)

  • text:输入框初始文本

5.2 常用属性与事件

  • 常用属性:

    • type(InputType):输入类型,Normal(普通)| Password(密码)| Number(数字)

    • caretColor(Color):光标颜色

    • placeholderFont():占位符字体样式

    • placeholderColor(Color):占位符颜色

  • 常用事件:

    • onChange((value: string) => void):输入内容变化

    • onFocus(() => void):获得焦点

    • onBlur(() => void):失去焦点

5.3 TextInput组件完整代码示例

// TextInputDemo.ets
@Entry
@Component
struct TextInputDemo {
  @State username: string = ''
  @State password: string = ''

  build() {
    Column({ space: 20 }) {
      // 1. 普通输入框
      TextInput({ placeholder: '请输入用户名' })
        .width('100%')
        .height(40)
        .padding(10)
        .border({ width: 1, color: '#CCCCCC' })
        .borderRadius(5)
        .caretColor('#007DFF')
        .onChange((value) => {
          this.username = value
          console.log(`用户名:${value}`)
        })
        .onFocus(() => {
          console.log('用户名输入框获得焦点')
        })
        .onBlur(() => {
          console.log('用户名输入框失去焦点')
        })

      // 2. 密码输入框
      TextInput({ placeholder: '请输入密码' })
        .type(InputType.Password)
        .width('100%')
        .height(40)
        .padding(10)
        .border({ width: 1, color: '#CCCCCC' })
        .borderRadius(5)
        .placeholderFont({ size: 14, weight: FontWeight.Normal })
        .placeholderColor('#999999')
        .onChange((value) => {
          this.password = value
        })

      // 3. 数字输入框
      TextInput({ placeholder: '请输入手机号' })
        .type(InputType.Number)
        .width('100%')
        .height(40)
        .padding(10)
        .border({ width: 1, color: '#CCCCCC' })
        .borderRadius(5)

      // 4. 登录按钮
      Button('登录')
        .width('100%')
        .height(40)
        .backgroundColor('#007DFF')
        .onClick(() => {
          console.log(`登录信息:用户名=${this.username}, 密码=${this.password}`)
        })
    }
    .padding(20)
    .width('100%')
  }
}

六、Progress 进度条组件

6.1 组件概述

  • 组件名Progress

  • 应用场景:文件下载、视频播放、音量调节、任务加载等需展示进度的场景。

6.2 组件参数

Progress(options: { value: number, total?: number, type?: ProgressType })

参数

类型

必填

说明

value

number

当前进度值

total

number

进度总值,默认100

type

ProgressType

进度条类型,默认ProgressType.Linear

ProgressType 枚举值

枚举值

说明

ProgressType.Linear

线性样式(默认)

ProgressType.Ring

环形样式

ProgressType.Eclipse

月食样式

ProgressType.ScaleRing

带刻度的环形样式

ProgressType.Capsule

胶囊样式

6.3 常用属性

  • style():样式设置

progress.style({
  strokeWidth?: number,    // 进度条宽度(Linear/Ring/ScaleRing)
  scaleCount?: number,      // 刻度线个数(仅ScaleRing)
  scaleWidth?: number       // 刻度线宽度(仅ScaleRing)
})
  • color(Color):进度条前景色(已完成部分)

  • backgroundColor(Color):进度条背景色(未完成部分)

6.4 Progress 完整代码示例

// ProgressDemo.ets
@Entry
@Component
struct ProgressDemo {
  @State currentValue: number = 30 // 当前进度
  @State totalValue: number = 100  // 总进度

  build() {
    Column({ space: 30 }) {
      // 1. 线性进度条
      Column({ space: 10 }) {
        Text('线性进度条')
        Progress({ value: this.currentValue, total: this.totalValue, type: ProgressType.Linear })
          .width('90%')
          .height(10)
          .color('#007DFF')
          .backgroundColor('#E5E5E5')
          .style({ strokeWidth: 10 })
      }

      // 2. 环形进度条
      Column({ space: 10 }) {
        Text('环形进度条')
        Progress({ value: this.currentValue, total: this.totalValue, type: ProgressType.Ring })
          .width(100)
          .height(100)
          .color('#FF9800')
          .style({ strokeWidth: 8 })
      }

      // 3. 月食进度条
      Column({ space: 10 }) {
        Text('月食进度条')
        Progress({ value: this.currentValue, total: this.totalValue, type: ProgressType.Eclipse })
          .width(100)
          .height(100)
          .color('#4CAF50')
      }

      // 4. 带刻度环形进度条
      Column({ space: 10 }) {
        Text('带刻度环形进度条')
        Progress({ value: this.currentValue, total: this.totalValue, type: ProgressType.ScaleRing })
          .width(100)
          .height(100)
          .color('#9C27B0')
          .style({
            strokeWidth: 5,
            scaleCount: 20,
            scaleWidth: 3
          })
      }

      // 5. 胶囊进度条(横向)
      Column({ space: 10 }) {
        Text('胶囊进度条(横向)')
        Progress({ value: this.currentValue, total: this.totalValue, type: ProgressType.Capsule })
          .width(200)
          .height(40)
          .color('#00BCD4')
      }

      // 6. 胶囊进度条(纵向)
      Column({ space: 10 }) {
        Text('胶囊进度条(纵向)')
        Progress({ value: this.currentValue, total: this.totalValue, type: ProgressType.Capsule })
          .width(40)
          .height(150)
          .color('#FF5722')
      }

      // 进度控制按钮
      Row({ space: 30 }) {
        Button('进度减一')
          .onClick(() => {
            if (this.currentValue > 0) {
              this.currentValue--
            }
          })

        Text(`当前进度:${this.currentValue}/${this.totalValue}`)
          .fontSize(16)

        Button('进度加一')
          .onClick(() => {
            if (this.currentValue < this.totalValue) {
              this.currentValue++
            }
          })
      }
    }
    .padding(20)
    .width('100%')
  }
}

七、弹窗组件

7.1 Toast 消息提示

7.1.1 概述

  • 用于显示简短消息或提示,短暂停留后自动消失。

  • 需导入@ohos.promptAction模块。

7.1.2 使用方法

import promptAction from '@ohos.promptAction'

promptAction.showToast(options: {
  message: string,        // 提示信息
  duration?: number,       // 停留时长(1500-10000ms),默认1500ms
  bottom?: string | number // 距离屏幕底部的距离
})

7.1.3 代码示例

// ToastDemo.ets
import promptAction from '@ohos.promptAction'

@Entry
@Component
struct ToastDemo {
  build() {
    Column({ space: 20 }) {
      Button('显示默认Toast')
        .onClick(() => {
          promptAction.showToast({
            message: '这是一条默认Toast'
          })
        })

      Button('显示长时长Toast')
        .onClick(() => {
          promptAction.showToast({
            message: '这条Toast会停留3秒',
            duration: 3000
          })
        })

      Button('显示底部Toast')
        .onClick(() => {
          promptAction.showToast({
            message: '距离底部100vp',
            bottom: '100vp'
          })
        })
    }
    .padding(20)
    .width('100%')
  }
}

7.2 AlertDialog 警告对话框

7.2.1 概述

  • 用于向用户发出警告或确认操作(如删除确认)。

  • 全局方法,直接调用alertDialog.show

7.2.2 使用方法

alertDialog.show(options: {
  title?: string,                          // 标题
  message?: string,                        // 内容
  autoClose?: boolean,                     // 点击遮障层是否关闭,默认true
  alignment?: DialogAlignment,             // 弹窗位置(Top/Center/Bottom)
  offset?: { dx: number, dy: number },    // 位置偏移量
  primaryButton?: {                        // 主要按钮
    text: string,
    color?: Color,
    action: () => void
  },
  secondaryButton?: {                      // 次要按钮
    text: string,
    color?: Color,
    action: () => void
  },
  cancel?: () => void                      // 点击遮罩层取消回调
})

7.2.3 代码示例

// AlertDialogDemo.ets
@Entry
@Component
struct AlertDialogDemo {
  build() {
    Column({ space: 20 }) {
      Button('显示简单警告框')
        .onClick(() => {
          alertDialog.show({
            title: '提示',
            message: '这是一条警告信息',
            primaryButton: {
              text: '确定',
              action: () => {
                console.log('点击了确定')
              }
            }
          })
        })

      Button('显示确认删除框')
        .onClick(() => {
          alertDialog.show({
            title: '删除确认',
            message: '确定要删除这条记录吗?删除后无法恢复!',
            autoClose: false,
            alignment: DialogAlignment.Center,
            primaryButton: {
              text: '取消',
              color: '#999999',
              action: () => {
                console.log('点击了取消')
              }
            },
            secondaryButton: {
              text: '删除',
              color: '#FF5722',
              action: () => {
                console.log('点击了删除,执行删除操作')
              }
            },
            cancel: () => {
              console.log('点击了遮罩层')
            }
          })
        })
    }
    .padding(20)
    .width('100%')
  }
}

7.3 ActionSheet 操作列表弹窗

7.3.1 概述

  • 包含一系列操作选项,用户选择后触发对应回调。

  • 全局方法,直接调用actionSheet.show

7.3.2 使用方法

actionSheet.show(options: {
  title?: string,                          // 标题
  message?: string,                        // 内容
  autoClose?: boolean,                     // 点击遮障层是否关闭
  alignment?: DialogAlignment,             // 弹窗位置
  offset?: { dx: number, dy: number },    // 偏移量
  confirm?: {                              // 底部确认按钮
    text: string,
    color?: Color,
    action: () => void
  },
  cancel?: () => void,                     // 点击遮罩层取消回调
  sheet: Array<{                           // 操作列表
    icon?: string,
    title: string,
    action: () => void
  }>
})

7.3.3 代码示例

// ActionSheetDemo.ets
@Entry
@Component
struct ActionSheetDemo {
  build() {
    Column({ space: 20 }) {
      Button('显示操作列表')
        .onClick(() => {
          actionSheet.show({
            title: '请选择操作',
            message: '选择以下选项之一',
            autoClose: true,
            alignment: DialogAlignment.Bottom,
            confirm: {
              text: '取消',
              color: '#007DFF',
              action: () => {
                console.log('点击了底部取消')
              }
            },
            cancel: () => {
              console.log('点击了遮罩层')
            },
            sheet: [
              {
                title: '拍照',
                action: () => {
                  console.log('选择了拍照')
                }
              },
              {
                title: '从相册选择',
                action: () => {
                  console.log('选择了从相册选择')
                }
              },
              {
                title: '保存图片',
                action: () => {
                  console.log('选择了保存图片')
                }
              }
            ]
          })
        })
    }
    .padding(20)
    .width('100%')
  }
}

7.4 文本选择器弹窗

7.4.1 概述

  • 让用户从预定义列表中选择具体值。

  • 全局方法,调用textPickerDialog.show

7.4.2 使用方法

textPickerDialog.show(options: {
  range: string[],                        // 选择范围(字符串数组)
  selected?: number,                       // 初始选中索引,默认0
  onAccept?: (value: string, index: number) => void, // 点击确定回调
  onCancel?: () => void,                   // 点击取消回调
  onChange?: (value: string, index: number) => void  // 选中内容变化回调
})

7.4.3 代码示例

// TextPickerDemo.ets
@Entry
@Component
struct TextPickerDemo {
  @State selectedFruit: string = '苹果'
  @State selectedIndex: number = 0
  private fruits: string[] = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']

  build() {
    Column({ space: 20 }) {
      Text(`当前选择:${this.selectedFruit}(索引:${this.selectedIndex})`)
        .fontSize(18)

      Button('打开水果选择器')
        .onClick(() => {
          textPickerDialog.show({
            range: this.fruits,
            selected: this.selectedIndex,
            onAccept: (value: string, index: number) => {
              this.selectedFruit = value
              this.selectedIndex = index
              console.log(`确定选择:${value},索引:${index}`)
            },
            onCancel: () => {
              console.log('点击了取消')
            },
            onChange: (value: string, index: number) => {
              console.log(`当前选中:${value},索引:${index}`)
            }
          })
        })
    }
    .padding(20)
    .width('100%')
  }
}

7.5 自定义弹窗

7.5.1 定义流程

  1. 定义struct结构体,使用@CustomDialog装饰器装饰

  2. 声明controller: CustomDialogController属性控制弹窗开关

  3. 实现build()方法声明UI结构

  4. 主页面中定义CustomDialogController,调用open()方法启动弹窗

7.5.2 代码示例

// CustomDialogDemo.ets
@Entry
@Component
struct CustomDialogDemo {
  @State answer: string = ''
  // 定义弹窗控制器
  private dialogController: CustomDialogController = new CustomDialogController({
    builder: AnswerDialog({
      onConfirm: (value: string) => {
        this.answer = value
      }
    }),
    autoCancel: true
  })

  build() {
    Column({ space: 20 }) {
      Text(`你的答案:${this.answer}`)
        .fontSize(18)

      Button('打开答题弹窗')
        .onClick(() => {
          this.dialogController.open()
        })
    }
    .padding(20)
    .width('100%')
  }
}

// 自定义答题弹窗
@CustomDialog
struct AnswerDialog {
  controller: CustomDialogController
  @State inputAnswer: string = ''
  // 回调函数:将输入的答案传回主页面
  onConfirm: (value: string) => void

  build() {
    Column({ space: 20 }) {
      Text('请输入你的答案')
        .fontSize(18)
        .fontWeight(FontWeight.Bold)

      TextInput({ placeholder: '请输入答案' })
        .width('100%')
        .height(40)
        .onChange((value) => {
          this.inputAnswer = value
        })

      Row({ space: 20 }) {
        Button('取消')
          .width('40%')
          .onClick(() => {
            this.controller.close()
          })

        Button('确定')
          .width('40%')
          .backgroundColor('#007DFF')
          .onClick(() => {
            this.onConfirm(this.inputAnswer)
            this.controller.close()
          })
      }
    }
    .padding(20)
    .width('80%')
    .backgroundColor(Color.White)
    .borderRadius(10)
  }
}
Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐