OpenHarmony中创建按钮主要通过**ArkUI(声明式UI)或传统AbilitySlice(命令式UI)**两种方式,以下是常见场景的实现:
Button组件,支持设置文本、类型、样式及事件。// pages/index.ets
@Entry
@Component
struct MyButtonPage {
build() {
Column({ space: 20, alignItems: Alignment.Center }) {
// 普通按钮(带点击事件)
Button('点击我')
.onClick(() => console.log('按钮被点击'))
.width('200px')
.height('50px')
// 胶囊按钮(type="capsule")
Button('胶囊按钮')
.type(ButtonType.Capsule)
.backgroundColor('#007DFF')
// 圆形按钮(通过自定义样式实现)
Button('')
.type(ButtonType.Circle)
.width('60px')
.height('60px')
.borderRadius(30)
.backgroundColor('#FF0000')
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
}
}
Button类创建,需手动设置布局。// MyAbilitySlice.ets
import { Button, Column, AbilitySlice } from '@ohos/ability/ui';
export default class MyAbilitySlice extends AbilitySlice {
onCreate(want, launchParam) {
super.onCreate(want, launchParam);
// 创建按钮
const button = new Button(this.context);
button.setText('命令式按钮');
button.setWidth(200);
button.setHeight(50);
// 添加到布局
const column = new Column();
column.addComponent(button);
this.setUIContent(column);
}
}
按钮的核心功能是响应用户交互,常见的事件包括点击、长按、触摸:
Button('登录')
.onClick(() => {
// 执行登录逻辑
console.log('开始登录...');
})
Button('长按我')
.onLongPress(() => {
console.log('按钮被长按');
})
Button('触摸反馈')
.onTouch((event) => {
switch (event.action) {
case TouchAction.Down:
console.log('手指按下');
break;
case TouchAction.Up:
console.log('手指抬起');
break;
}
return true; // 返回true表示事件已消费
})
通过style属性或CSS(HML方式)调整按钮外观,提升用户体验:
Button('自定义按钮')
.type(ButtonType.Normal)
.borderRadius(20) // 圆角
.backgroundColor('#4CAF50') // 背景色
.fontColor(Color.White) // 文字颜色
.fontSize(16) // 文字大小
.width('250px')
.height('60px')
<!-- pages/index.hml -->
<div class="container">
<button
class="custom-btn"
type="normal"
onclick="handleClick"
>
自定义按钮
</button>
</div>
/* pages/index.css */
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.custom-btn {
border-radius: 25px;
background-color: #2196F3;
color: white;
font-size: 18px;
padding: 12px 30px;
border: none;
}
OpenHarmony支持多种按钮类型,满足不同场景需求:
type="capsule",两端圆角,适合导航栏或工具栏。Button('胶囊')
.type(ButtonType.Capsule)
.backgroundColor('#FF9800')
type="circle"或自定义borderRadius实现,适合悬浮操作(如添加按钮)。Button('')
.type(ButtonType.Circle)
.width(50)
.height(50)
.backgroundColor('#F44336')
type="download",内置下载进度显示,需配合setProgress方法更新进度。Button('下载')
.type(ButtonType.Download)
.id('downloadBtn')
.onClick(() => {
// 模拟下载进度
let progress = 0;
const interval = setInterval(() => {
progress += 10;
this.$element('downloadBtn').setProgress(progress);
if (progress >= 100) clearInterval(interval);
}, 500);
})
config.json中添加网络权限:{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
Flex或Column布局确保按钮在不同屏幕尺寸下正确显示。通过以上步骤,可实现OpenHarmony中按钮的创建、事件处理、样式自定义及特殊类型应用,满足大多数场景的需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。