鸿蒙开发之android开发指南《基础组件》

2,204 阅读6分钟

同android开发一样,华为鸿蒙官方也提供了很多基础组件,下面介绍几种容器组件和常用基础组件的使用方式。

一、容器组件

鸿蒙组件描述
Column沿垂直方向布局的容器
Row沿水平方向布局容器
RelativeContainer相对约束布局容器组件
Flex以弹性方式布局子组件的容器组件
Grid网格容器组件
GridRow栅格容器组件
List沿水平方向布局容器组件
Tabs标签页容器组件

1.Column&Row 排列容器组件

Column竖向排列容器组件,等同于竖向的LinerLayout。Row横向排列的容器组件,等同于横向的LinerLayou。使用方法如下:

Column() {
  Text("1")
  ...
  Text("2")
  ...
  Text("")
  ...
}

image.png

Row() {
  Text("1")
  ...
  Text("2")
  ...
  Text("3")
  ...
}

image.png

关键属性:

属性名称作用描述
justifyContent设置子组件在主轴方向上的对齐格式Colmun-FlexAlign属性参考Row-VerticalAlign属性参考
alignItems设置子组件在交叉轴方向上的对齐格Column-HorizontalAlign属性参考Row-VerticAlalig属性参考

2.RelativeContainer 相对布局容器组件

RleativeContainer相当于android中的RelativeLayout,使用方式如下:

RelativeContainer() {
  Text("1")
    .fontSize(32)
    .fontColor(Color.White)
    .alignRules({
      top: { anchor: "__container__", align: VerticalAlign.Top },
      left: { anchor: "__container__", align: HorizontalAlign.Start }
    })
    .id("one_txt")
    .width(50)
    .height(50)
    .textAlign(TextAlign.Center)
    .backgroundColor(Color.Green)

  Text("2")
    .fontSize(32)
    .fontColor(Color.White)
    .alignRules({
      top: { anchor: "one_txt", align: VerticalAlign.Top },
      left: { anchor: "one_txt", align: HorizontalAlign.End }
    })
    .id("two_txt")
    .width(50)
    .height(50)
    .textAlign(TextAlign.Center)
    .backgroundColor(Color.Red)
  Text("3")
    .fontSize(32)
    .fontColor(Color.White)
    .alignRules({
      top: { anchor: "two_txt", align: VerticalAlign.Bottom },
      left: { anchor: "one_txt", align: HorizontalAlign.End }
    })
    .id("three_txt")
    .width(50)
    .height(50)
    .textAlign(TextAlign.Center)
    .backgroundColor(Color.Blue)

}.width("100%").height("100%")

image.png

首先需要给子组件设置"id",然后通过"alignRules"定义规则,“anchor”锚点。详细规则见官网

3.List 列表组件

List列表展示组件,同Listview,List组件包含两种子组件ListItemListItemGroup,下面是List的简单使用:

@Component
export struct ListUi {
  @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"]

  build() {
    Column() {
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item) => {
          ListItem() {
            Text('' + item)
              .width('100%')
              .height(100)
              .fontSize(16)
              .textAlign(TextAlign.Center)
              .borderRadius(10)
              .backgroundColor(0xFFFFFF)
          }
          .border({ width: 2, color: Color.Green })
        }, item => item)
      }
      .height("100%")
      .width("100%")
      .padding(20)
    }
  }
}

image.png

关键属性和接口:

属性或者接口名称描述
ListDirection(..)排列方向(竖向Axis.Vertical、横向Axis.Horizontal)
space子控件主方向上的间隔
initialIndex设置当前List初次加载时视口起始位置显示的item的索引值
scroller可滚动组件的控制器。用于与可滚动组件进行绑定
divider设置ListItem分割线样式,默认无分割线
cachedCount设置列表中ListItem/ListItemGroup的预加载数量,其中ListItemGroup将作为一个整体进行计算,ListItemGroup中的所有ListItem会一次性全部加载出来
lanes9+api 9新增,以列模式为例(listDirection为Axis.Vertical),lanes用于决定List组件在交叉轴方向按几列布局。
onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void)滚动事件监听
其它参考官方文档

4.Grid 网格组件

Grid网格布局组件,同GridView,简单使用方式如下:

@State Number: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']

build() {
  Grid() {
    ForEach(this.Number, (day: string) => {
      GridItem() {
        Text(day)
          .fontSize(16)
          .backgroundColor(0xF9CF93)
          .width('20%')
          .height(100)
          .textAlign(TextAlign.Center)
      }
    }, day => day)
  }
  .width('100%')
  .backgroundColor(Color.White)
  .height('100%')
}

image.png

关键属性和接口:

属性或接口名称描述
columnsTemplate设置当前网格布局列的数量,不设置时默认1列。例如, '1fr 1fr 2fr' 是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。
rowsTemplate设置当前网格布局行的数量,不设置时默认1行。例如,'1fr 1fr 2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。
columnsGap设置列与列的间距
rowsGap设置行与行的间距
GridDirection沿主轴布局方向

还有很多api,参考官网

二、常用基础组件

android组件鸿蒙组件描述
TextViewText用于文本显示
EditTextTextInput用于文本文本输入
ButtonButton用于点击按钮
ImageViewImage图片显示

1.Text 文本显示控件

同TextView,主要用于文本显示,简单使用方式如下:

Text("文本显示控件 超长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长")
  .fontColor(Color.Green)
  .fontSize(24)
  .width("100%")
  .maxLines(2)
  .textOverflow({ overflow: TextOverflow.Ellipsis })

image.png

关键属性:

名称描述
textAlign设置文本段落在水平方向的对齐方式默认值:TextAlign.Start
textOverflow设置文本超长时的显示方式。默认值:{overflow: TextOverflow.Clip}
maxLines设置文本的最大行数
lineHeight设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp
decoration设置文本装饰线样式及其颜色
letterSpacing设置文本字符间距
minFontSize设置文本最小显示字号
maxFontSize设置文本最大显示字号

2.TextInput 文本输入控件

同EditText,文本输入控件,简单使用如下:

TextInput({ placeholder: '请输入密码' })
  .width(400)
  .height(40)
  .margin(20)
  .type(InputType.Password)
  .maxLength(9)
  .showPasswordIcon(true)

image.png

关键属性:

名称描述
type设置输入框类型(密码、数字、邮箱等)
placeholderColor设置placeholder文本颜色
placeholderFont设置placeholder文本样式
enterKeyType设置输入法回车键类型,目前仅支持默认类型显示
caretColor设置输入框光标颜色
maxLength设置文本的最大输入字符数
inputFilter8+正则表达式,匹配表达式的输入允许显示,不匹配的输入将被过滤。目前仅支持单个字符匹配,不支持字符串匹配
textAlign9+设置输入文本在输入框中的对齐方式
onChange(callback: (value: string) => void)输入内容发生变化时,触发该回调
onSubmit(callback: (enterKey: EnterKeyType) => void)按下输入法回车键触发该回调,返回值为当前输入法回车键的类型
onEditChange(callback: (isEditing: boolean) => void)8+输入状态变化时,触发该回调

3.Button 按钮控件

Button常见的按钮点击控件,使用方法如下:

Button('OK', { type: ButtonType.Normal, stateEffect: true })
  .borderRadius(8)
  .backgroundColor(0x317aff)
  .width(90)
  .onClick(() => {
    console.log('click ok')
  })
  .margin({ top: 20, left: 20 })

Button({ type: ButtonType.Circle, stateEffect: true }) {
  LoadingProgress().width(20).height(20).color(0xFFFFFF)
}.width(55).height(55).backgroundColor(0x317aff).margin({ top: 20 })

Button({ type: ButtonType.Circle, stateEffect: true }) {
  LoadingProgress().width(20).height(20).color(0xFFFFFF)
}.width(55).height(55).margin({ top: 20 }).backgroundColor(0xF55A42)

image.png

关键属性:

名称描述
type按钮显示样式(胶囊样式、圆、普通样式)
stateEffect按钮按下时是否开启按压态显示效果
onClick()点击事件

4.Image 图片加载控件

Image同ImageView,用于图片展示,支持png、jpg、bmp、svg和gif类型的图片格式。下面加载图片和网络图片案例:

Image($r('app.media.test_bg')).width(400).width(400)
Text("本地图片").width("100%").textAlign(TextAlign.Center).fontSize(22).fontColor(Color.Black).margin({top:20})

Image("https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500").width(400).width(400).margin({top:40})
Text("网络图片").width("100%").textAlign(TextAlign.Center).fontSize(22).fontColor(Color.Black).margin({top:20})

image.png 注意网络图片需要在module.json里面配置网络权限:ohos.permission.INTERNET

关键属性:

名称描述
alt加载时显示的占位图,支持本地图片(png、jpg、bmp、svg和gif类型),不支持网络图片
objectFit设置图片的填充效果。
fitOriginalSize图片组件尺寸未设置时,显示尺寸是否跟随图源尺寸
autoResize设置图片解码过程中是否对图源自动缩放。设置为true时,组件会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。
onComplete加载完成事件
onError加载失败事件