实现效果如下图:
为了好分析,我们将界面分为两部分,标注如下:
很明显区域1和区域2是垂直关系,用Colum容器,区域1又分为左右两部分,是水平关系,大容器使用的是Row,左边是Iamge,右边是垂直布局,使用Cloum容器,从上往下分别是Text+Text+Row+Text+Text,区域2也是整体是水平方向,Row+Text+Colum+Text+Text+Button,逻辑是:点击事件,添加或者是减少商品的个数,根据选择的商品件数和价格计算出总的钱。代码如下:
@Entry @Component struct IndexTest { @State TotalNum:number = 1 build() { Column() { Column() { // 产品 Row({ space: 10}){ // 图片 Image($r('app.media.product1')) .width(100) .borderRadius(8) // 文字 Column({space: 10}) { Column({ space: 6}) { Text('冲销量1000ml缤纷八果水果捞') .lineHeight(20) .fontSize(14) Text('含1份折扣商品') .fontSize(12) .fontColor('#7f7f7f') } .width('100%') .alignItems(HorizontalAlign.Start) Row(){ // 价格 Row({ space: 5}) { Text() { Span('¥') .fontSize(14) Span('20.2') .fontSize(18) } .fontColor('#ff4000') Text() { Span('¥') Span('40.4') } .fontSize(14) .fontColor('#999') .decoration({type: TextDecorationType.LineThrough, color: '#999'}) } // 加减 Row() { Text('-') .width(22) .height(22) .border({width:1, color: '#e1e1e1', radius: {topLeft: 5, bottomLeft: 5}}) .textAlign(TextAlign.Center) .fontWeight(700) .onClick(()=>{ if(this.TotalNum >=2){ this.TotalNum -=1 } }) Text(this.TotalNum.toString()) .height(22) .border({width: { top:1, bottom: 1 }, color: '#e1e1e1'}) .padding({left: 10, right: 10}) .fontSize(14) Text('+').onClick(()=>{ this.TotalNum+=1 }) .width(22) .height(22) .border({width:1, color: '#e1e1e1', radius: {topRight: 5, bottomRight: 5}}) .textAlign(TextAlign.Center) .fontWeight(700) } } .width('100%') .justifyContent(FlexAlign.SpaceBetween) } .height(75) .layoutWeight(1) .justifyContent(FlexAlign.SpaceBetween) } .width('100%') .alignItems(VerticalAlign.Top) .padding(20) // 结算 Row({ space: 10 }){ // 价格 Column({space: 5}) { Text() { Span(`已选${this.TotalNum}件,`) .fontColor('#848484') Span('合计:') Span('¥') .fontColor('#fd4104') Span((this.TotalNum*20.2).toFixed(2)) .fontColor('#fd4104') .fontSize(16) } .fontSize(14) Text('共减¥20.2') .fontColor('#fd4104') .fontSize(12) } .alignItems(HorizontalAlign.End) // 结算按钮 Button('结算外卖') .width(110) .height(40) .backgroundColor('#fed70e') .fontColor('#564200') .fontSize(16) .fontWeight(600) } .width('100%') .height(70) .backgroundColor('#fff') .position({x:0, y: '100%'}) .translate({y: '-100%'}) .padding({ left: 20, right: 20 }) .justifyContent(FlexAlign.End) } } .width('100%') .height('100%') .backgroundColor('#f3f3f3') } }
总结:鸿蒙界面布局最外层通常是Colum或者是Row,先总体,嵌套,图片使用Image、文本使用Text,数据更新需要显示到界面只需要使用State修饰变量即可,点击事件是onClick,嵌套在Text的还会有span,用与指定特定文字的属性修改,我们把 .position({x:0, y: '100%'})和 .translate({y: '-100%'})注释掉,显示效果如下图:
.translate({y: '-100%'}) -100%的意思是y轴的反方向移动自身组件的多少,如果不要这一句,只是加.position({x:0, y: '100%'})这一句的话会在底部显示不完全,其实不要这一句,改为.position({x:0, y: '90%'})效果也不错。