第九节HarmonyOS 常用基础组件4-Button

一、Button

Button组件主要用来响应点击操作,可以包含子组件。

示例代码:

复制代码
@Entry
@Component
struct Index {
  build() {
    Row() {
      Column() {
        Button('确定', { type: ButtonType.Capsule, stateEffect: true })
          .width('90%')
          .height(40)
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .backgroundColor('#007DFF')

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

效果图:

二、设置按钮样式

type用于定义按钮样式,示例代码中ButtonType.Capsule表示胶囊形按钮;stateEffect用于设置按钮按下时是否开启切换效果,当状态置为false时,点击效果关闭,默认值为true。

我们可以设置多种样式的Button,除了Capsule可以以设置Normal和Circle:

代码:

复制代码
@Entry
@Component
struct Index {
  build() {
    Row() {
      Column() {
        Button('确定', { type: ButtonType.Normal, stateEffect: true })
          .width('90%')
          .height(50)
          .fontSize(20)
          .backgroundColor('#007DFF')
        Blank(10)
        Button('确定1', { type: ButtonType.Capsule, stateEffect: true })
          .width('90%')
          .height(50)
          .fontSize(20)
          .backgroundColor('#007DFF')
        Blank(10)
        Button('确定', { type: ButtonType.Circle, stateEffect: true })
          .width('90%')
          .height(100)
          .fontSize(20)
          .backgroundColor('#007DFF')

      }
      .width('100%')
    }
    .height('100%')
  }
}
  1. Capsule:胶囊型按钮(圆角默认为高度的一半)。
  1. Circle:圆形按钮。
  1. Normal:普通按钮(默认不带圆角)。

三、设置按钮点击事件

可以给Button绑定onClick事件,每当用户点击Button的时候,就会回调执行onClick方法,调用里面的逻辑代码。

复制代码
Button('登录', { type: ButtonType.Capsule, stateEffect: true })
  ...
  .onClick(() => {
  // 处理点击事件逻辑
  })

四、包含子组件

Button组件可以包含子组件,让您可以开发出更丰富多样的Button,下面的示例代码中Button组件包含了一个Image组件:

复制代码
Button({ type: ButtonType.Circle, stateEffect: true }) {
  Image($r('app.media.icon_delete'))
    .width(30)
    .height(30)
}
.width(55)
.height(55)
.backgroundColor(0x317aff)

效果图如下:

相关推荐
爱笑的眼睛114 小时前
深入探讨HarmonyOS分布式剪贴板:技术原理与开发实践
华为·harmonyos
特立独行的猫a6 小时前
鸿蒙PC平台三方库移植实战:以libogg库移植为例(附完整移植流程与工具链配置)
华为·harmonyos·三方库移植·鸿蒙pc·libogg
爱笑的眼睛116 小时前
深入理解HarmonyOS通知渠道与优先级设置:从基础到高级实践
华为·harmonyos
夏文强10 小时前
HarmonyOS开发者认证练习题-判断题
华为·harmonyos
Kisang.10 小时前
【HarmonyOS】ArkTS的多线程并发(下)——线程间通信对象的传递
华为·typescript·harmonyos·鸿蒙
柒儿吖15 小时前
Qt for HarmonyOS 3D图片轮播组件开源鸿蒙开发实战
qt·3d·harmonyos
fuze233315 小时前
解决在虚拟机的ensp中启动路由器,卡0%且出现虚拟机卡死的方法
网络·华为·ensp
爱笑的眼睛1119 小时前
HarmonyOS分布式输入法开发:实现多设备无缝输入体验
华为·harmonyos
爱笑的眼睛1119 小时前
深入HarmonyOS打印服务:从基础到高级应用开发
华为·harmonyos
鸿蒙小白龙1 天前
OpenHarmony内核开发实战手册:编译构建、HCK框架与性能优化
harmonyos·鸿蒙·鸿蒙系统·open harmony