问题现象
ProgressButton默认不支持高度调整,如何实现可调高度的下载按钮?
解决方案
- 方案逻辑:Progress组件可以配置高度,使用Progress的属性可实现与ProgressButton相同的下载效果。
- 通过Progress组件的style属性的content参数,实现在Progress组件上显示按钮文字和进度信息。
Progress({ value: this.progressIndex, total: 100, type: ProgressType.Capsule })
.width(300)
.height(100) // 设置Progress组件的高度
.color(Color.Blue)
.margin({top:300})
.style({
borderWidth: 1,
content: this.textState, // 设置按钮文字
font: { size: 13, style: FontStyle.Normal },
enableScanEffect: false,
showDefaultPercentage: false
}) - 给Progress添加点击事件,控制Progress上显示内容的变化。初始时,显示为“下载”;点击后动态显示下载进度,再次点击后显示“继续”,并且暂停下载进度;进度100%后,显示为“完成”。
.onClick(() => {
this.isRunning = !this.isRunning;
if (this.textState && !this.isRunning && this.progressIndex < 100) {
this.textState = '继续';
}
let timer = setInterval(() => {
if (this.isRunning && this.progressIndex < 100) {
this.progressIndex++;
this.textState = `${this.progressIndex}%`;
if (this.progressIndex === 100) {
this.textState = '已完成';
this.isRunning = false;
}
} else {
clearInterval(timer);
}
}, 20);
}) - 设置Progress组件的高度。
Progress({ value: this.progressIndex, total: 100, type: ProgressType.Capsule })
.width(300)
.height(100) // 设置Progress组件的高度
- 完整示例参考如下:
@Entry
@Component
struct PushButton {
@State progressIndex: number = 0;
@State textState: string = '下载';
@State isRunning: boolean = false;
build() {
Column({ space: 20 }) {
Progress({ value: this.progressIndex, total: 100, type: ProgressType.Capsule })
.width(300)
.height(100) // 设置Progress组件的高度
.color(Color.Blue)
.margin({top:300})
.style({
borderWidth: 1,
content: this.textState, // 设置按钮文字
font: { size: 13, style: FontStyle.Normal },
enableScanEffect: false,
showDefaultPercentage: false
})
.onClick(() => {
this.isRunning = !this.isRunning;
if (this.textState && !this.isRunning && this.progressIndex < 100) {
this.textState = '继续';
}
let timer = setInterval(() => {
if (this.isRunning && this.progressIndex < 100) {
this.progressIndex++;
this.textState = `${this.progressIndex}%`;
if (this.progressIndex === 100) {
this.textState = '已完成';
this.isRunning = false;
}
} else {
clearInterval(timer);
}
}, 20);
})
}.alignItems(HorizontalAlign.Center).width('100%').margin({ top: 20 })
}
}