首先声明数字键盘并定义其样式,使用 keyBoxStyle 将键盘样式抽取出来,之后直接调用即可:
numbers:string[]=['0','1','2','3','4','5','6','7','8','9','.']//定义键盘
@Styles keyBoxStyle(){
.backgroundColor(Color.White)
.borderRadius(8)
.height(60)
}
build() {
Grid(){
ForEach(this.numbers,num =>{
GridItem(){
Text(num).fontSize(20).fontWeight(CommonConstants.FONT_WEIGHT_900)
}
.keyBoxStyle()
})
GridItem(){
Text('删除').fontSize(20).fontWeight(CommonConstants.FONT_WEIGHT_900)
}
.keyBoxStyle()
}
.width('100%')
.height(300)
.backgroundColor($r('app.color.index_page_background'))
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(8)
.rowsGap(8)//行间距
.padding(8)
}
实现效果:
接下来是键盘点击时间,包括输入的判断、数值的转换、删除事件等等,具体在代码注释中展示:
clickNumber(num:string){//点击数值
//1.拼接用户输入的内容
let val = this.value + num
//2.校验输入格式
let firstIndex=val.indexOf('.')//从第一个开始数小数点位置
let lastIndex=val.lastIndexOf('.')//从后往前数
if (firstIndex !== lastIndex || (lastIndex)!= -1 && lastIndex <val.length -2) {
//有两个小数点或者小数点位数超过两位
//非法输入
return
}
//3.将字符串转为数值
let amount = this.parseFloat(val)//格式化
//4.保存
if (amount >= 999.9) {//确保不会超出上限
this.amount=999.0
this.value='999'
}else {
this.amount=amount
this.value=val
}
}
clickDelete(){
if (this.value.length <= 0) {
this.value=''
this.amount=0
return
}
this.value=this.value.substring(0,this.value.length-1)
this.amount=this.parseFloat(this.value)
}
parseFloat(str:string){
if(!str){//删除到最后
return 0
}
if (str.endsWith('.')) {
str=str.substring(0,str.length-1)
}
return parseFloat(str)
}
还有最终的按钮点击事件:
//3.4按钮
Row({space:CommonConstants.SPACE_6}){
Button('取消')
.width(120)
.backgroundColor($r('app.color.light_gray'))
.type(ButtonType.Normal)
.borderRadius(6)
.onClick(()=>this.showPanel=false)
Button('提交')
.width(120)
.backgroundColor($r('app.color.primary_color'))
.type(ButtonType.Normal)
.borderRadius(6)
.onClick(()=>this.showPanel=false)
}
.margin({top:10})
实现效果: