3.1、HarmonyOS Next 按钮 Button

37 阅读1分钟

Button是按钮组件,通常用于响应用户的点击操作,其类型包括胶囊按钮、圆形按钮、普通按钮。Button当做为容器使用时可以通过添加子组件实现包含文字、图片等元素的按钮。

我开发的 Demo 展示

在这里插入图片描述

以下代码均经过我 demo 的实战验证,确保代码和效果对应

创建按钮

Button通过调用接口来创建,接口调用有以下两种形式:

创建不包含子组件的按钮

在这里插入图片描述

Button('Ok', { type: ButtonType.Normal, stateEffect: true }) 
  .borderRadius(8) 
  .backgroundColor(0x317aff) 
  .width(90)
  .height(40)

创建包含子组件的按钮

在这里插入图片描述

Button({ type: ButtonType.Normal, stateEffect: true }) {
   Row() {
  Image($r("app.media.ic_loading")).width(20).height(20).margin({ left: 12 })
    Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
  }.alignItems(VerticalAlign.Center)
}
.borderRadius(8)
.backgroundColor(0x317aff)
.width(90)
.height(40)

设置按钮类型

Button 有三种可选类型,分别为 Capsule(胶囊类型)、Circle(圆形按钮)和 Normal(普通按钮),通过type进行设置。

胶囊按钮(默认类型)

在这里插入图片描述

Button('Disable', { type: ButtonType.Capsule, stateEffect: false })
	.backgroundColor(0x317aff)
	.width(90)
	.height(40)

圆形按钮

在这里插入图片描述

 Button('Circle', { type: ButtonType.Circle, stateEffect: false })
	.backgroundColor(0x317aff)
	.width(90)
	.height(90)

普通按钮

在这里插入图片描述

Button('Ok', { type: ButtonType.Normal, stateEffect: true })
    .borderRadius(8)
    .backgroundColor(0x317aff)
    .width(90)
    .height(40)

自定义样式

设置边框弧度

在这里插入图片描述

 Button('circle border', { type: ButtonType.Normal })
              .borderRadius(20)
              .height(40)

设置文本样式

在这里插入图片描述

Button('font style', { type: ButtonType.Normal })
              .fontSize(20)
              .fontColor(Color.Pink)
              .fontWeight(800)

设置背景颜色

在这里插入图片描述

  Button('background color')
       .backgroundColor(0xF55A42)

用作功能型按钮

在这里插入图片描述

Button({ type: ButtonType.Circle, stateEffect: true }) {
    Image($r('app.media.ic_delete_filled'))
    .width(30)
    .height(30)
   }
   .width(55)
   .height(55)
   .margin({ left: 20 })
   .backgroundColor(0xF55A42)

添加事件

Button('Ok', { type: ButtonType.Normal, stateEffect: true }) 
  .onClick(()=>{ 
    console.info('Button onClick') 
  })

上一篇 2.10、创建轮播(Swiper) 下一篇 3.2、单选框(Radio)