Demo1:任务列表案例
实现图:
代码:
// 任务类
@Observed
class Task{
static id: number = 1
// 任务名称
name: string = `任务${Task.id++}`
// 任务状态:是否完成
finished: boolean = false
}
// 统一的卡片样式
@Styles function card(){
.width('95%')
.padding(20)
.backgroundColor(Color.White)
.borderRadius(15)
.shadow({radius: 6, color: '#1F000000', offsetX: 2, offsetY: 4})
}
// 任务完成样式
@Extend(Text) function finishedTask(){
.decoration({type:TextDecorationType.LineThrough})
.fontColor('#B1B2B1')
}
class StateInfo{
totalTask:number = 0
finishTask:number = 0
}
@Entry
@Component
struct PropPage {
@State stat:StateInfo = new StateInfo()
build(){
Column({space:10}){
TaskStatistics({finishTask:this.stat.finishTask,totalTask:this.stat.totalTask})
TaskList({stat:$stat})
}
.width('100%')
.height('100%')
.backgroundColor('#F1F2F3')
}
}
@Component
struct TaskStatistics{
@Prop finishTask:number
@Prop totalTask:number
build(){
Row(){
Text('任务进度:')
.fontSize(30)
.fontWeight(FontWeight.Bold)
Stack(){//堆叠容器
Progress({
value:this.finishTask,
total:this.totalTask,
type:ProgressType.Ring
})
.width(100)
Row(){
Text(this.finishTask.toString())
.fontSize(24)
.fontColor('#36D')
Text('/'+this.totalTask.toString())
.fontSize(24)
}
}
}
.card()
.margin({top:20,bottom:10})
.justifyContent(FlexAlign.SpaceEvenly)
}
}
@Component
struct TaskList{
@Link stat:StateInfo
@State tasks:Task[] = []
handleTaskChange(){
this.stat.totalTask = this.tasks.length
this.stat.finishTask = this.tasks.filter(item=>item.finished).length
}
build() {
Column(){
Button('新增任务')
.width(200)
.margin({bottom:10})
.onClick(()=>{
this.tasks.push(new Task())
this.handleTaskChange()
})
List({space:10}){
ForEach(
this.tasks,
(item:Task,index)=>{
ListItem(){
TaskItem({ item:item ,onTaskChange:this.handleTaskChange.bind(this)})
}
.swipeAction({ end: this.DeleteButton(index) })
}
)
}
.width('100%')
.layoutWeight(1)
.alignListItem(ListItemAlign.Center)
}
}
@Builder DeleteButton(index:number){
Button(){
Image($r('app.media.delete'))
.fillColor(Color.Black)
.width(20)