鸿蒙应用开发(第三章:常用组件)

系列文章目录

鸿蒙应用开发(第一章:快速体验)
鸿蒙应用开发(第二章:开发语言)
鸿蒙应用开发(第三章:常用组件)



1. 图片

1.1 概述

Image为图片组件,用于在应用中显示图片。

1.2 参数

Image组件的参数类型为string | Resource | media.PixelMap

@Entry
@Component
struct ImageParameter {
  build() {
    Column({ space: 40 }) {
      //本地图片,位于ets目录
      Image('pages/component/image/parameter/solution/images/img_phone.png')
        .width(150)
        .height(150)

      //网络图片
      Image('https://developer.harmonyos.com/resource/image/new/home/img_DLP_jiazhi_2.png')
        .width(150)
        .height(150)

      //本地图片,位于resource/*/media目录
      Image($r('app.media.img_harmony'))
        .width(150)
        .height(150)

      //本地图片,位于resource/rawfile目录
      Image($rawfile('img_phone.png'))
        .width(150)
        .height(150)

    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

下面对三种参数类型逐一进行介绍。

  • string类型

string类型的参数用于通过路径的方式引用图片,包括本地图片和网络图片。

本地图片:

Image('images/demo.jpg')

注意:使用这种方式引入本地图片,需要将图片置于ets目录下,并且需要为Image组件提供图片相对于ets目录的路径。

网络图片:

Image('http://xxx/xxx.jpg')

注意:真机中运行的鸿蒙应用,访问网络图片需要配置网络访问权限,不过在预览器和模拟器中测试时不受限制。权限配置相关的内容在后续章节会系统介绍。

  • Resource类型

Resource类型的参数用于引入 resources 目录下的图片。

resources目录用于统一存放应用所需的各种资源,包括图片、音频、视频、文本等等。下面简要介绍 resources 目录的用法,首先需要了解 resources 的目录结构,如下

在这里插入图片描述

resources 目录下,用于存放资源的子目录有(elementmediaprofile)和rawfile。下面分别介绍

element、media、profile:

elementmediaprofile)可存在多种版本,用于适配不同的环境,例如语言环境(zh_CNen_US)、系统主题(darklight)、设备类型(phonetablet) 等等。我们可以为上述每种环境各自准备一套资源文件,每种环境对应 resources 下的一个目录,例如上述的 zh_CNen_US。我们在使用resources下的资源时,无需指定具体的环境版本,系统会根据设备所处的环境自动选择匹配的版本,例如当设备系统语言为中文时,则会使用zh_CN目录下的资源,为英文时,则会使用en_US目录下的资源。若没有与当前所处环境相对应的版本,则使用 base 目录下资源。

各目录存储的具体资源如下:

  1. media
    存放媒体资源,包括图片、音频、视频等文件。
  2. element
    存放用于描述页面元素的尺寸、颜色、样式等的各种类型的值,每种类型的值都定义在一个相应的 JSON 文件中。
  3. profile
    存放自定义配置文件。

rawfile:

用于存储任意格式的原始文件,需要注意的是rawfile不会根据设备所处的环境去匹配不同的资源。

总结:

resources目录下可用于存放图片的目录有resources/*/media 以及 resources/rawfile,两个目录下图片的使用方式有所不同,下面逐一介绍

  1. media目录
    该目录下的资源,需要使用$r('app.media.<filename>')的方式引用。

注意:无需指定具体版本,系统会自动根据所处环境选择相应版本

例如上图中的img.png图片,可通过$r('app.media.img')引用。需要注意的是$r()的返回值即为 Resource 类型,因此可以直接将$r('app.media.img')作为 Image 组件的参数,例如Image($r('app.media.img'))

  1. rawfile目录
    该目录下的资源,可通过$rawfile('path/to/your/file')的方式引用,文件的路径为相对于 rawfile 的路径。例如上图中的icon.png,须使用$rawfile('icon.png)引用。需要注意的是,$rawfile()的返回值也是Resource类型,因此其也可以直接作为 Image 组件的参数,如Image($rawfile('icon.png))
  • media.PixelMap

PixelMap指的是图片的像素位图,其通常是一个二维数组,数组中的每个元素对应着图片中的一个像素,其包含了该像素的颜色等信息。像素位图主要用于图片编辑的场景,例如

在这里插入图片描述

1.3 常用属性

1.3.1 图片尺寸

图片尺寸可通过width()方法和height()方法进行设置。例如

Image($r('app.media.img'))
	.width(100)
	.height(100)

两个方法可接收的参数类型均为string | number | Resource

@Entry
@Component
struct ImageSizePage {
  build() {
    Column({ space: 20 }) {

      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
          Text('宽高:450px')
        }

        Column() {
          Image($r('app.media.img_harmony'))
            .width('150vp')
            .height('150vp')
          Text('宽高:150vp')
        }
      }

      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_harmony'))
            .width(150)
            .height(150)
          Text('宽高:150')
        }

        Column() {
          Image($r('app.media.img_harmony'))
            .width($r('app.integer.width'))
            .height($r('app.integer.height'))
          Text('宽高:150')
        }
      }

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
  • string类型

string类型的参数可为百分比,例如'100%',或者为具体尺寸,例如'100px'

具体尺寸的单位,常用的有两个,分别是pxvp,下面逐个介绍

前置知识(屏幕参数)

想要理解上述尺寸单位,需要大家先掌握屏幕相关的几个参数

  1. 像素
    屏幕显示的最小单位,屏幕上的一个小亮点称为一个像素。
  2. 分辨率
    屏幕上横向和纵向的像素数量。
  3. 尺寸
    屏幕对角线的长度,以英寸(inches)为单位。
  4. 像素密度
    像素密度是每英寸屏幕上的像素数量,通常以PPI(Pixels Per Inch)表示,计算公式如下。较高的像素密度意味着在相同尺寸的屏幕上有更多的像素,从而提供更加清晰和细腻的图像。

在这里插入图片描述

如下图所示

在这里插入图片描述

px(Pixel):

物理像素,以像素个数来定义图像尺寸。这种方式的弊端是,在不同像素密度的屏幕上,相同的像素个数对应的物理尺寸是不同的。这样一来就会导致我们的应用在不同设备上显示的尺寸可能不同。如下图所示

在这里插入图片描述

vp(Virtual Pixel):

为了保证一致的观感,我们可以使用虚拟像素作为单位。虚拟像素是一种可根据屏幕像素密度灵活缩放的单位。1vp相当于像素密度为160ppi的屏幕上的1px。在不同像素密度的屏幕上,HarmonyOS会根据如下公式将虚拟像素换算为对应的物理像素

在这里插入图片描述

根据上述公式,不难看出,使用虚拟像素作为单位时,同一尺寸,在像素密度低的屏幕上(单个像素的物理尺寸大),对应的物理像素会更少,相反在像素密度高的屏幕上(单个像素的物理尺寸小),对应的物理像素会更多。因此就能在不同像素密度的屏幕上,获得基本一致的观感了。如下图所示

在这里插入图片描述

  • number类型

number类型的参数,默认以vp作为单位。

  • Resource类型

Resource类型参数用于引用resources下的element目录中定义的数值。

引用element目录中的数值,同样需要使用$r()函数。要了解具体语法,需要先熟悉element目录下的文件内容。

前文提到过,element目录中可保存各种类型的数值,且每种类型的值分别定义在一个JSON文件中。文件中的内容为键值对(name-value)的形式。具体内容如下

element/string.json:
{
  "string": [
    {
      "name": "module_desc",
      "value": "模块描述"
    },
    {
      "name": "greeting",
      "value": "你好"
    }
  ]
}
element/integer.json:
{
  "integer": [
    {
      "name": "width",
      "value": 150
    },
    {
      "name": "height",
      "value": 150
    }
  ]
}

我们可以通过 name 引用相应的 value。具体语法为$r('app.<data_type>.<name>')

注意:无需指定具体版本,系统会自动根据所处环境选择相应版本

例如上述的 greeting 的值,可通过$r('app.string.greeting')引用,width的值可通过$r('app.integer.width')

1.3.2 图片缩放

当图片的原始大小与Image组件不同时,可通过objectFit()方法来设置图片的显示效果。该方法的参数类型为ImageFit枚举类型,可选的枚举值如下

名称描述
ImageFit.None保持原有尺寸显示,不做任何缩放,超出显示区域的部分不显示。
ImageFit.Contain保持宽高比进行缩小或者放大,使得显示区域刚好包含整个图片。
ImageFit.Cover保持宽高比进行缩小或者放大,使得图片刚好完全覆盖显示区域。
ImageFit.Fill不保持宽高比进行放大缩小,使得图片充满显示区域。
ImageFit.ScaleDown保持宽高比进行缩小或不变(不会放大),使得图片完全显示在显示区域内。
ImageFit.Auto自适应显示

各选项的效果如下图所示

在这里插入图片描述

@Entry
@Component
struct ImageObjectFit {
  build() {
    Column({ space: 20 }) {

      Column() {
        Image($r('app.media.img_harmony'))
          .width('720px')
          .height('334px')
        Text('原图')
      }

      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
            .borderWidth(1)
            .objectFit(ImageFit.None)
          Text('None')
        }

        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
            .borderWidth(1)
            .objectFit(ImageFit.Contain)
          Text('Contain')
        }
      }

      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
            .borderWidth(1)
            .objectFit(ImageFit.Cover)
          Text('Cover')
        }

        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
            .borderWidth(1)
            .objectFit(ImageFit.Fill)
          Text('Fill')
        }
      }

      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
            .borderWidth(1)
            .objectFit(ImageFit.ScaleDown)
          Text('ScaleDown')
        }

        Column() {
          Image($r('app.media.img_harmony'))
            .width('450px')
            .height('450px')
            .borderWidth(1)
            .objectFit(ImageFit.Auto)
          Text('Auto')
        }
      }
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}

1.3.3 图片插值

当原图分辨率较低并且需要放大显示时,图片会模糊并出现锯齿。如下图所示

在这里插入图片描述

这时可以使用interpolation()方法对图片进行插值,使图片显示得更清晰。该方法的参数为ImageInterpolation枚举类型,可选的值有

名称描述
ImageInterpolation.None不使用图片插值。
ImageInterpolation.High高质量插值,可能会影响图片渲染的速度。
ImageInterpolation.Medium中等质量插值。
ImageInterpolation.Low低等质量插值。

各选项效果如下图所示

在这里插入图片描述

@Entry
@Component
struct ImageInterpolationPage {
  build() {
    Column({ space: 50 }) {
      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_flower'))
            .width('500px')
            .height('500px')
            .interpolation(ImageInterpolation.None)
          Text('None')
        }

        Column() {
          Image($r('app.media.img_flower'))
            .width('500px')
            .height('500px')
            .interpolation(ImageInterpolation.Low)
          Text('Low')
        }
      }


      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_flower'))
            .width('500px')
            .height('500px')
            .interpolation(ImageInterpolation.Medium)
          Text('Medium')

        }

        Column() {
          Image($r('app.media.img_flower'))
            .width('500px')
            .height('500px')
            .interpolation(ImageInterpolation.High)
          Text('High')
        }
      }
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2. 文本

2.1 概述

Text为文本组件,用于显示文字内容。

2.2 参数

Text组件的参数类型为string | Resource,下面分别对两个参数类型进行介绍:

  • string类型
Text('我是一段文本')
  • Resource 类型

Resource类型的参数用于引用 resources/*/element目录中定义的字符串,同样需要使用$r()引用。
例如resources/base/element目录中有一个string.json文件,内容如下

{
  "string": [
    {
      "name": "greeting",
      "value": "你好"
    }
  ]
}

此时我们便可通过如下方式引用并显示greeting的内容。

Text($r('app.string.greeting'))
@Entry
@Component
struct TextParameterPage {
  build() {
    Column({ space: 50 }) {
      //字符串类型
      Text('你好,鸿蒙')
        .fontSize(50)

      //Resource类型
      Text($r('app.string.greeting'))
        .fontSize(50)
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2.3 常用属性

2.3.1 字体大小

字体大小可通过fontSize()方法进行设置,该方法的参数类型为string | number| Resource,下面逐一介绍

  • string类型

string类型的参数可用于指定字体大小的具体单位,例如fontSize('100px'),字体大小的单位支持pxfp。其中fp(font pixel)vp类似,具体大小也会随屏幕的像素密度变化而变化。

  • number类型

number类型的参数,默认以fp作为单位。

  • Resource类型

Resource类型参数用于引用resources下的element目录中定义的数值。

@Entry
@Component
struct FontSizePage {
  build() {
    Column({ space: 50 }) {
      Text('你好,鸿蒙')
        .fontSize('150px')

      Text('你好,鸿蒙')
        .fontSize('50fp')

      Text('你好,鸿蒙')
        .fontSize(50)
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2.3.2 字体粗细

字体粗细可通过fontWeight()方法进行设置,该方法参数类型为number | FontWeight | string,下面逐一介绍

  • number类型

number类型的取值范围是[100,900],取值间隔为100,默认为400,取值越大,字体越粗。

  • FontWeight类型

FontWeight为枚举类型,可选枚举值如下

名称描述
FontWeight.Lighter字体较细。
FontWeight.Normal字体粗细正常。
FontWeight.Regular字体粗细正常。
FontWeight.Medium字体粗细适中。
FontWeight.Bold字体较粗。
FontWeight.Bolder字体非常粗。
  • string类型

string类型的参数仅支持number类型和FontWeight类型参数的字符串形式,例如例如'100'bold

@Entry
@Component
struct FontWeightPage {
  build() {
    Column({ space: 50 }) {

      //默认效果
      Text('你好,鸿蒙')
        .fontSize(50)

      Text('你好,鸿蒙')
        .fontSize(50)
        .fontWeight(666)

      Text('你好,鸿蒙')
        .fontSize(50)
        .fontWeight(FontWeight.Lighter)

      Text('你好,鸿蒙')
        .fontSize(50)
        .fontWeight('800')

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2.3.3 字体颜色

字体颜色可通过fontColor()方法进行设置,该方法参数类型为Color | string | number | Resource,下面逐一介绍

  • Color类型

Color为枚举类型,其中包含了多种常用颜色,例如Color.Green

  • string类型

string类型的参数可用于设置 rgb 格式的颜色,具体写法可以为'rgb(0, 128, 0)'或者'#008000'

  • number类型

number类型的参数用于使用16进制的数字设置 rgb 格式的颜色,具体写法为0x008000

  • Resource类型

Resource类型的参数用于应用resources下的element目录中定义的值。

@Entry
@Component
struct FontColorPage {
  build() {
    Column({ space: 50 }) {
      Text('Color.Green')
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
        .fontColor(Color.Green)

      Text('rgb(0, 128, 0)')
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
        .fontColor('rgba(59, 171, 59, 0.33)')

      Text('#008000')
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
        .fontColor('#a4008000')

      Text('0x008000')
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
        .fontColor(0xa4008000)

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2.3.4 文本对齐

文本对齐方向可通过textAlign()方法进行设置,该方法的参数为枚举类型TextAlign,可选的枚举值如下

名称描述
TextAlign.Start首部对齐
TextAlign.Center居中对齐
TextAlign.End尾部对齐

各选项效果如下

在这里插入图片描述

@Entry
@Component
struct TextAlignPage {
  build() {
    Column({ space: 50 }) {
      Column({ space: 10 }) {
        Text('鸿蒙操作系统是由华为公司开发的全场景、分布式的新一代操作系统,旨在实现各类智能设备的高效协同工作和统一体验')
          .fontSize(20)
          .width(300)
          .borderWidth(1)
          .textAlign(TextAlign.Start)
        Text('Start')
      }

      Column({ space: 10 }) {
        Text('鸿蒙操作系统是由华为公司开发的全场景、分布式的新一代操作系统,旨在实现各类智能设备的高效协同工作和统一体验')
          .fontSize(20)
          .width(300)
          .borderWidth(1)
          .textAlign(TextAlign.Center)
        Text('Center')
      }

      Column({ space: 10 }) {
        Text('鸿蒙操作系统是由华为公司开发的全场景、分布式的新一代操作系统,旨在实现各类智能设备的高效协同工作和统一体验')
          .fontSize(20)
          .width(300)
          .borderWidth(1)
          .textAlign(TextAlign.End)
        Text('End')
      }

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2.3.5 最大行数和超长处理

可使用maxLines()方法控制文本的最大行数,当内容超出最大行数时,可使用textOverflow()方法处理超出部分,该方法的参数类型为{ overflow: TextOverflow },其中TextOverflow为枚举类型,可用枚举值有

名称描述
TextOverflow.Clip文本超长时,进行裁剪显示。
TextOverflow.Ellipsis文本超长时,显示不下的文本用省略号代替。

各选项效果如下
在这里插入图片描述

@Entry
@Component
struct TextOverFlowPage {
  build() {
    Column({ space: 50 }) {
      Column({ space: 10 }) {
        Text('鸿蒙操作系统是由华为公司开发的全场景、分布式的新一代操作系统,旨在实现各类智能设备的高效协同工作和统一体验')
          .fontSize(20)
          .width(300)
          .borderWidth(1)
        Text('原始内容')
      }

      Column({ space: 10 }) {
        Text('鸿蒙操作系统是由华为公司开发的全场景、分布式的新一代操作系统,旨在实现各类智能设备的高效协同工作和统一体验')
          .fontSize(20)
          .width(300)
          .borderWidth(1)
          .maxLines(2)
          .textOverflow({ overflow: TextOverflow.Clip })
        Text('Clip')
      }

      Column({space:10}) {
        Text('鸿蒙操作系统是由华为公司开发的全场景、分布式的新一代操作系统,旨在实现各类智能设备的高效协同工作和统一体验')
          .fontSize(20)
          .width(300)
          .borderWidth(1)
          .maxLines(2)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
        Text('Ellipsis')
      }

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

3. 按钮

3.1 概述

Button为按钮组件,通常用于响应用户的点击操作。

3.2 参数

Button组件有两种使用方式,分别是不包含子组件包含子组件,两种方式下,Button组件所需的参数有所不同,下面分别介绍

不包含子组件:

不包含子组件时,Button组件所需的参数如下

Button(label?: string, options?: { type?: ButtonType, stateEffect?: boolean })
  1. label
    label为按钮上显示的文字内容。

  2. options.type
    options.type为按钮形状,该属性的类型ButtonType,可选的枚举值有

名称描述效果
ButtonType.Capsule胶囊形状在这里插入图片描述
ButtonType.Circle圆形在这里插入图片描述
ButtonType.Normal普通形状在这里插入图片描述
  1. options.stateEffect
    options.stateEffect表示是否开启点击效果,点击效果如下

在这里插入图片描述

包含子组件:

子组件会作为按钮上显示的内容,可以是图片、文字等。这种方式下,Button组件就不在需要label参数了,具体如下

Button(options?: {type?: ButtonType, stateEffect?: boolean})
@Entry
@Component
struct ButtonParameter {
  build() {
    Column({ space: 50 }) {

      //不包含子组件
      Button('按钮', { type: ButtonType.Capsule, stateEffect: false })
        .fontSize(25)
        .width(150)
        .height(60)

      //包含子组件
      Button({ type: ButtonType.Capsule, stateEffect: true }) {
        Row({ space: 5 }) {
          Image($r('app.media.icon_new_folder'))
            .width(30)
            .height(30)
          Text('新建')
            .fontColor(Color.White)
            .fontSize(25)
            .fontWeight(500)
        }
      }.height(60)
      .width(150)

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

3.3 常用属性

3.3.1 背景颜色

按钮的颜色可使用backgroundColor()方法进行设置,例如

Button('绿色按钮').backgroundColor(Color.Green)

3.3.2 边框圆角

按钮的边框圆角大小可使用borderRadius()方法进行设置,例如

Button('圆角按钮', { type: ButtonType.Normal }).borderRadius(10)
@Entry
@Component
struct ButtonAttributePage {
  build() {
    Column({ space: 50 }) {
      Button('绿色按钮')
        .fontSize(25)
        .width(150)
        .height(60)
        .backgroundColor(Color.Green)

      Button('圆角按钮', { type: ButtonType.Normal })
        .fontSize(25)
        .width(150)
        .height(60)
        .borderRadius(20)

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

3.4 常用事件

对于Button组件而言,最为常用的就是点击事件,可以通过onClick()方法为按钮绑定点击事件,该方法的参数为一个回调函数,当按钮被点击时,就会触发该回调函数,例如

Button('点击事件').onClick(() => {
  console.log('我被点击了')
})
@Entry
@Component
struct ButtonEventPage {
  build() {
    Column({ space: 50 }) {
      Button('点击事件')
        .fontSize(25)
        .width(150)
        .height(60)
        .onClick(() => {
          console.log('我被点击了')
        })


    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

4. 切换按钮

4.1 概述

Toggle为切换按钮组件,一般用于两种状态之间的切换,例如下图中的蓝牙开关。

在这里插入图片描述

4.2 参数

Toggle组件的参数定义如下

Toggle(options: { type: ToggleType, isOn?: boolean })
  • type

type属性用于设置Toggle组件的类型,可通过ToggleType枚举类型进行设置,可选的枚举值如下

名称描述效果
ToggleType.Switch开关在这里插入图片描述
ToggleType.Checkbox复选框在这里插入图片描述
ToggleType.Button按钮在这里插入图片描述
  • isOn

isOn属性用于设置Toggle组件的状态,例如

在这里插入图片描述

@Entry
@Component
struct ToggleParameter {
  build() {
    Column({ space: 20 }) {
      Row({ space: 20 }) {
        Toggle({ type: ToggleType.Switch, isOn: false })
        Toggle({ type: ToggleType.Switch, isOn: true })
      }

      Row({ space: 20 }) {
        Toggle({ type: ToggleType.Checkbox, isOn: false })
        Toggle({ type: ToggleType.Checkbox, isOn: true })
      }

      Row({ space: 20 }) {
        Toggle({ type: ToggleType.Button, isOn: false }) {
          Text('button')
        }

        Toggle({ type: ToggleType.Button, isOn: true }) {
          Text('button')
        }
      }
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

4.3 常用属性

4.3.1 选中状态背景色

可使用selectedColor()方法设置Toggle组件在选中(或打开)状态下的背景色,例如

在这里插入图片描述

4.3.2 Swtich滑块颜色

可使用设置switchPointColor()方法设置Switch类型的Toggle组件中的圆形滑块颜色,例如

在这里插入图片描述

4.4 常用事件

Toggle组件常用的事件为change事件,每当Toggle组件的状态发生变化,就会触发change事件。开发者可通过onChange()方法为Toggle组件绑定change事件,该方法参数为一个回调函数,具体定义如下

onChange(callback: (isOn: boolean) => void)

Toggle组件的状态由关闭切换为打开时,isOntrue,从打开切换为关闭时,isOnfalse

@Entry
@Component
struct LightPage {
  @State isOn: boolean = false;

  build() {
    Column({ space: 20 }) {
      if (this.isOn) {
        Image($r('app.media.img_light'))
          .height(300)
          .width(300)
          .borderRadius(20)
      } else {
        Image($r('app.media.img_dark'))
          .height(300)
          .width(300)
          .borderRadius(20)
      }
      Toggle({ type: ToggleType.Switch, isOn: this.isOn })
        .width(60)
        .height(30)
        .onChange((isOn) => {
          this.isOn = isOn;
        })
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

5. 文本输入

5.1 概述

TextInput为文本输入组件,用于接收用户输入的文本内容。

5.2 参数

TextInput组件的参数定义如下

TextInput(value?:{placeholder?: string|Resource , text?: string|Resource})
  • placeholder

placeholder属性用于设置无输入时的提示文本,效果如下

在这里插入图片描述

  • text

text用于设置输入框当前的文本内容,效果如下

在这里插入图片描述

@Entry
@Component
struct TextInputParameter {
  build() {
    Column({ space: 50 }) {
      TextInput({ placeholder: '请输入用户名' })
        .width('70%')

      TextInput({ text: '当前内容' })
        .width('70%')

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

5.3 常用属性

5.3.1 输入框类型

可通过type()方法设置输入框的类型,该方法的参数为InputType枚举类型,可选的枚举值有

名称描述
InputType.Normal基本输入模式
InputType.Password密码输入模式
InputType.Number纯数字输入模式

5.3.2 光标样式

可通过caretColor()方法设置光标的颜色,效果如下

在这里插入图片描述

5.3.3 placeholder样式

可通过placeholderFont()placeholderColor()方法设置 placeholder 的样式,其中placeholderFont()用于设置字体,包括字体大小、字体粗细等,placeholderColor()用于设置字体颜色,效果如下

在这里插入图片描述

5.3.4 文本样式

输入文本的样式可通过fontSize()fontWeight()fontColor()等通用属性方法进行设置。

@Entry
@Component
struct TextInputAttributePage {
  build() {
    Column({ space: 50 }) {

      Column({ space: 10 }) {
        Text('输入框类型')
        TextInput({ placeholder: '请输入任意内容' })
          .width('70%')
          .type(InputType.Normal)
        TextInput({ placeholder: '请输入数字' })
          .width('70%')
          .type(InputType.Number)
        TextInput({ placeholder: '请输入密码' })
          .width('70%')
          .type(InputType.Password)
      }

      Column({ space: 10 }) {
        Text('光标样式')
        TextInput()
          .width('70%')
          .caretColor(Color.Red)
      }

      Column({ space: 10 }) {
        Text('placeholder样式')
        TextInput({ placeholder: '请输入用户名' })
          .width('70%')
          .placeholderFont({ weight: 800 ,style:FontStyle.Italic})
          .placeholderColor('#66008000')
      }

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

5.4 常用事件

5.4.1 change事件

每当输入的内容发生变化,就会触发 change 事件,开发者可使用onChange()方法为TextInput组件绑定 change 事件,该方法的参数定义如下

onChange(callback: (value: string) => void)

其中value为最新内容。

5.4.2 焦点事件

焦点事件包括获得焦点失去焦点两个事件,当输入框获得焦点时,会触发 focus 事件,失去焦点时,会触发 blur 事件,开发者可使用onFocus()onBlur()方法为 TextInput 组件绑定相关事件,两个方法的参数定义如下

onFocus(event: () => void)	

onBlur(event: () => void)
@Entry
@Component
struct TextInputEvent {
  build() {
    Column({ space: 50 }) {
      TextInput({ placeholder: '请输入用户名' })
        .width('70%')
        .type(InputType.Normal)
        .onChange((value) => {
          console.log(`用户名:${value}`)
        })
        .onFocus(() => {
          console.log('用户名输入框获得焦点')
        })
        .onBlur(() => {
          console.log('用户名输入框失去焦点')
        })

      TextInput({ placeholder: '请输入密码' })
        .width('70%')
        .type(InputType.Password)
        .onChange((value) => {
          console.log(`密码:${value}`)
        })
        .onFocus(() => {
          console.log('密码输入框获得焦点')
        })
        .onBlur(() => {
          console.log('密码输入框失去焦点')
        })
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

6. 进度条

6.1 概述

Progress为进度条组件,用于显示各种进度。

6.2 参数

Progress组件的参数定义如下

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

value属性用于设置当前进度值。

  • total

total属性用于设置总值。

  • type

type属性用于设置进度条类型,可通过ProgressType枚举类型进行设置,可选的枚举值如下

名称描述效果
ProgressType.Linear线性样式在这里插入图片描述
ProgressType.Ring环形无刻度样式在这里插入图片描述
ProgressType.Eclipse月食样式在这里插入图片描述
ProgressType.ScaleRing环形有刻度样式在这里插入图片描述
ProgressType.Capsule胶囊样式在这里插入图片描述
@Entry
@Component
struct ProgressParameter {
  @State value: number = 30;
  @State total: number = 100;

  build() {
    Column({ space: 50 }) {
      Progress({ value: this.value, total: this.total, type: ProgressType.Linear })
      Progress({ value: this.value, total: this.total, type: ProgressType.Ring })
      Progress({ value: this.value, total: this.total, type: ProgressType.Eclipse })
      Progress({ value: this.value, total: this.total, type: ProgressType.ScaleRing })
      Progress({ value: this.value, total: this.total, type: ProgressType.Capsule })
        .width(50)
        .height(200)

      //分隔线
      Divider()

      Row({ space: 50 }) {
        Button('进度-1')
          .onClick(() => {
            if (this.value > 0) {
              this.value--;
            }
          })
        Button('进度+1')
          .onClick(() => {
            if (this.value < this.total) {
              this.value++;
            }
          })
      }
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

6.3 常用属性

6.3.1 进度条样式

可通过style()调整进度条的样式,例如进度条的宽度,该方法的参数类型定义如下

style({strokeWidth?: string|number|Resource,scaleCount?: number,scaleWidth?: string|number|Resource})
  • strokeWidth

strokeWidth属性用于设置进度条的宽度,默认值为4vp。该属性可用于LinearRingScaleRing三种类型,效果如下
在这里插入图片描述

  • scaleCount

scaleCount属性用于设置ScaleRing的刻度数,默认值为120。效果如下

在这里插入图片描述

  • scaleWidth

scaleCount属性用于设置ScaleRing的刻度线的宽度,默认值为2vp。效果如下

在这里插入图片描述

@Entry
@Component
struct ProgressAttributePage {
  build() {
    Column({ space: 50 }) {
      Progress({ value: 30, total: 100, type: ProgressType.Linear })
        .style({
          strokeWidth: 20
        })

      Progress({ value: 30, total: 100, type: ProgressType.Ring })
        .style({
          strokeWidth: 20
        })

      Progress({ value: 30, total: 100, type: ProgressType.ScaleRing })
        .style({
          strokeWidth: 10,
          scaleWidth: 3,
          scaleCount: 30
        })

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

6.3.2 进度条颜色

进度条的颜色可通过color()backgroundColor()方法进行设置,其中color()用于设置前景色,backgroundColor()用于设置背景色,例如

在这里插入图片描述

@Entry
@Component
struct ProgressColor {
  build() {
    Column({ space: 50 }) {
      Progress({ value: 30, total: 100, type: ProgressType.Linear })
        .color(Color.Green)
        .backgroundColor("#26008000")

      Progress({ value: 30, total: 100, type: ProgressType.Ring })
        .color(Color.Green)
        .backgroundColor("#26008000")

      Progress({ value: 30, total: 100, type: ProgressType.Eclipse })
        .color(Color.Green)
        .backgroundColor("#26008000")

      Progress({ value: 30, total: 100, type: ProgressType.ScaleRing })
        .color(Color.Green)
        .backgroundColor("#26008000")

      Progress({ value: 30, total: 100, type: ProgressType.Capsule })
        .width(200)
        .color(Color.Green)
        .backgroundColor("#26008000")

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

7. 弹窗

弹窗是移动应用中常见的一种用户界面元素,常用于显示一些重要的信息、提示用户进行操作或收集用户输入。ArkTS提供了多种内置的弹窗供开发者使用,除此之外还支持自定义弹窗,来满足各种不同的需求。

7.1 消息提示

7.1.1 概述

Toast(消息提示),常用于显示一些简短的消息或提示,一般会在短暂停留后自动消失。具体效果如下

在这里插入图片描述

7.1.2 使用说明

可使用@ohos.promptAction模块中的showToast()方法显示 Toast 提示,使用时需要先导入@ohos.promptAction模块,如下

import promptAction from '@ohos.promptAction'

showToast()方法的参数定义如下

showToast(options: { message: string | Resource,duration?: number,bottom?: string | number})
  • message

message属性用于设置提示信息

  • duration

duration属性用于设置提示信息停留时长,单位为毫秒,取值范围是[1500,10000]

  • bottom

bottom属性用于设置提示信息到底部的距离

import promptAction from '@ohos.promptAction';

@Entry
@Component
struct ToastPage {
  build() {
    Column() {
      Button('提示信息')
        .onClick(() => {
          promptAction.showToast({
            message: '网络连接已断开',
            duration: 2000,
            bottom: 50
          });
        })
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

7.2 警告对话框

7.2.1 概述

AlertDialog(警告对话框)用于向用户发出警告或确认操作的提示,确保用户在敏感操作前进行确认。具体效果如下

在这里插入图片描述

@Entry
@Component
struct AlertDialogPage {
  build() {
    Column() {
      Button('删除')
        .backgroundColor(Color.Red)
        .onClick(() => {
          AlertDialog.show(
            {
              title: '删除该记录?', //弹窗标题
              message: '删除后无法恢复,您确认要删除吗?', //弹窗信息
              autoCancel: true, //点击遮障层时,是否关闭弹窗
              alignment: DialogAlignment.Bottom, //弹窗位置
              offset: { dx: 0, dy: -20 }, //相对于弹窗位置的偏移量
              primaryButton: { //主要按钮,位于左侧
                value: '确认', //按钮内容
                fontColor: Color.Red, //字体颜色
                action: () => { //点击回调
                  console.log('确认删除')
                }
              },
              secondaryButton: { //次要按钮,位于右侧
                value: '取消',
                action: () => {
                  console.log('取消删除')
                }
              },
              cancel: () => { //点击遮罩层取消时的回调
                console.info('Closed callbacks')
              }
            }
          )
        })

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

7.2.2 使用说明

可使用全局方法AlertDialog.show()显示警告对话框,具体用法可参考相关案例或者官方文档

7.3 操作列表弹框

7.3.1 概述

ActionSheet(操作列表弹窗)用于提供一组选项给用户选择,用户从中选择后,可执行相应的操作。具体效果如下

在这里插入图片描述

@Entry
@Component
struct ActionSheetPage {
  build() {
    Column() {
      Button('选择操作')
        .onClick(() => {
          ActionSheet.show({
            title: '文件操作', //弹窗标题
            message: '请选择你要对该文件执行的操作', //弹窗内容
            autoCancel: true, //点击遮障层时,是否关闭弹窗
            alignment: DialogAlignment.Bottom, //弹窗位置
            offset: { dx: 0, dy: -20 }, //弹窗相对alignment位置的偏移量
            confirm: { //底部按钮
              value: '取消', //按钮文本内容
              action: () => { //按钮回调函数
                console.log('点击按钮取消')
              }
            },
            // cancel: () => { //点击遮障层关闭弹窗时的回调
            //   console.log('点击遮障层取消')
            // },
            sheets: [ //操作选项列表
              {
                icon: $r('app.media.icon_copy'), //图标
                title: '复制', //文本
                action: () => { //回调
                  console.log('复制文件')
                }
              },
              {
                icon: $r('app.media.icon_cut'),
                title: '剪切',
                action: () => {
                  console.log('剪切文件')
                }
              },
              {
                icon: $r('app.media.icon_delete'),
                title: '删除',
                action: () => {
                  console.log('删除文件')
                }
              }
            ]
          })
        })
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

7.3.2 使用说明

可使用全局方法ActionSheet.show()显示操作列表弹窗,具体用法可参考相关案例或者官方文档

7.4 选择器弹窗

7.4.1 概述

选择器弹窗用于让用户从一个列表中选择一个具体的值。ArkTS内置了多种选择器弹窗,例如文本选择器、日期选择器、时间选择器等等,各选择器效果如下

TextPickerDialog(文本滑动选择器弹窗):

@Entry
@Component
struct TextPickerDialogPage {
  fruits: string[] = ['苹果', '橘子', '香蕉', '鸭梨', '西瓜']
  @State selectedIndex: number = 0

  build() {
    Column({ space: 50 }) {
      Text(this.fruits[this.selectedIndex])
        .fontWeight(FontWeight.Bold)
        .fontSize(30)

      Button("选择文本")
        .margin(20)
        .onClick(() => {
          TextPickerDialog.show({
            range: this.fruits, //设置文本选择器的选择范围
            selected: this.selectedIndex, //设置选中的索引
            onAccept: (value: TextPickerResult) => { //确定按钮的回调函数
              this.selectedIndex = value.index;
            },
            onCancel: () => { //取消按钮的回调函数
              console.info('取消选择')
            },
            onChange: (value: TextPickerResult) => { //选择器选中内容发生变化时触发的回调函数
              console.info(`当前文本:${JSON.stringify(value)}`)
            }
          })
        })
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

DatePickerDialog(日期滑动选择期弹窗):

@Entry
@Component
struct DatePickerDialogPage {
  @State date: Date = new Date("2010-1-1");

  build() {
    Column({ space: 50 }) {
      Text(`${this.date.getFullYear()}${this.date.getMonth() + 1}${this.date.getDate()}`)
        .fontWeight(FontWeight.Bold)
        .fontSize(30)

      Button("选择日期")
        .margin(20)
        .onClick(() => {
          DatePickerDialog.show({
            start: new Date("2000-1-1"), //设置选择器的其实日期
            end: new Date("2100-12-31"), //设置选择器的结束日期
            selected: this.date, //设置当前选中的日期
            onAccept: (value: DatePickerResult) => { //确定按钮的回调
              this.date.setFullYear(value.year, value.month, value.day)
            },
            onCancel: () => { //取消按钮的回调
              console.info('取消选择')
            },
            onChange: (value: DatePickerResult) => { //选择器当前内容发生变化时触发的回调函数
              console.info(`当前日期:${JSON.stringify(value)}`)
            }
          })
        })

    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

TimePickerDialog(时间滑动选择器弹窗):

@Entry
@Component
struct TimePickerDialogPage {
  @State time: Date = new Date('2020-01-01T00:00:00')

  build() {
    Column({ space: 50 }) {

      Text(`${this.time.getHours()}:${this.time.getMinutes()}`)
        .fontWeight(FontWeight.Bold)
        .fontSize(30)

      Button("选择时间")
        .margin(20)
        .onClick(() => {
          TimePickerDialog.show({
            selected: this.time, //设置当前选中的时间
            useMilitaryTime: true, //是否使用24小时制
            onAccept: (value: TimePickerResult) => { //确认按钮的回调
              this.time.setHours(value.hour, value.minute);
            },
            onCancel: () => { //取消按钮的回调
              console.info('取消选择')
            },
            onChange: (value: TimePickerResult) => { //选择器当前内容发生变化时触发的回调函数
              console.info(`当前时间:${JSON.stringify(value)}`)
            }
          })
        })
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

7.4.2 使用说明

具体用法可参考相关案例或者官方文档,各选择器的官方文档地址如下

类型文档地址
TextPickerDialog(文本滑动选择器弹窗)官方文档
DatePickerDialog(日期滑动选择期弹窗)官方文档
TimePickerDialog(时间滑动选择器弹窗)官方文档

7.5 自定义弹窗

7.5.1 概述

当现有组件不满足要求时,可考虑自定义弹窗,自定义弹窗允许开发者自定义弹窗内容和样式。例如

@Entry
@Component
struct CustomDialogPage {
  @State answer: string = '?'
  controller: CustomDialogController = new CustomDialogController({
    builder: TextInputDialog({
      confirm: (value) => {
        this.answer = value;
      }
    }),
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -30 }
  })

  build() {
    Column({ space: 50 }) {
      Row() {
        Text('1+1=')
          .fontWeight(FontWeight.Bold)
          .fontSize(30)
        Text(this.answer)
          .fontWeight(FontWeight.Bold)
          .fontSize(30)
      }

      Button('作答')
        .onClick(() => {
          this.controller.open();
        })
    }.width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}


@CustomDialog
struct TextInputDialog {
  controller: CustomDialogController = new CustomDialogController({ builder: TextInputDialog() })
  confirm: (value: string) => void;
  value: string = '';

  build() {
    Column({ space: 20 }) {
      Text('请输入你的答案')
      TextInput({ placeholder: '请输入数字' })
        .type(InputType.Number)
        .onChange((value) => {
          this.value = value;
        })
      Row({ space: 50 }) {
        Button('取消')
          .onClick(() => {
            this.controller.close();
          })
        Button('确认').onClick(() => {
          this.confirm(this.value);
          this.controller.close();
        })
      }
    }.padding(20)
  }
}

7.5.2 使用说明

显示自定义弹窗需要使用CustomDialogController,具体用法可参考相关案例或者官方文档

  • 29
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值