Harmony实战之简易计算器

news2025/5/18 8:35:28

前言

臭宝们,在学会上一节的基础知识之后,我们来实战一下。

预备知识

我们需要用到的知识点有:

  1. Column组件
  2. Row组件
  3. @Link装饰器
  4. button组件
  5. TextInput组件
  6. @State装饰器

最终效果图

在这里插入图片描述

代码实现

index页面(首页)

/**
* @program:
*
* @description:
 *
*
* @author: 槐月
*
* @create: 2025/4/9-21:11
**/
//import用来引入组件。
import {button_Item}from '../Item/button_Item'
@Entry
@Component
struct Index {
    //fontTitleSize和fontSubTitleSize是用来控制字体大小的。
  @State fontTitleSize:number = 35;
  @State fontSubTitleSize:number = 15;
  //TitleInput和SubInput是用来控制输入框的。
  @State TitleInput:string ='0';
  @State SubInput:string  = '';
  build() {
     Column(){
        Column(){
          TextInput({text:this.TitleInput.toString()})
            .copyOption(CopyOptions.None)
            .minFontSize(5)
            .maxFontSize(this.fontTitleSize)
            .enabled(false)//禁用输入框
            .textOverflow(100)
            .textAlign(TextAlign.End)
            .backgroundColor('#75878a')
          TextInput({text:this.SubInput})
            .enabled(false)
            .minFontSize(5)
            .maxFontSize(this.fontSubTitleSize)
            .backgroundColor('#75878a')
            .textAlign(TextAlign.End)
        }
        .justifyContent(FlexAlign.End)
        .backgroundColor('#75878a')
        .margin({
          top:20,
          bottom:140
        })
        .padding({
          right:5

        })
        .border({
          width:2,
          color:Color.White
        })
        .borderRadius(10)
        .height('20%')
        .alignItems(HorizontalAlign.End)
        .width('90%')
        button_Item({fontTopItem:this.fontTitleSize,
          fontEndItem:this.fontSubTitleSize,
          currentInput:this.TitleInput,previousValueString:this.SubInput})
     }
     .backgroundColor('#c0c6c9')
     .width('100%')
    .height('100%')
  }
}

在上面这段代码中,我们使用了Column组件来布局。在Column里面我们又嵌套了一个Column用来放置输入框和按钮。fontTitleSize和fontSubTitleSize是用来控制字体大小的。TitleInput和SubInput是用来控制输入框的。
在Column中内嵌的Column做了以下设置:

  1. borderRadius(10)是为了让输入框的边框圆角更加明显。
  2. height(‘20%’)是为了让输入框的高度占整个页面的20%。
  3. width(‘90%’)是为了让输入框的宽度占整个页面的90%。
  4. alignItems(HorizontalAlign.End)是为了让输入框的内容向右对齐。
  5. justifyContent(FlexAlign.End)是为了让输入框的内容向下对齐。
  6. padding({right:5})是为了让输入框的内容向右偏移。
  7. margin({top:20,bottom:140})是为了让输入框的内容向下偏移。
  8. border({width:2,color:Color.White})是为了让输入框的边框更加明显,并且颜色为白色。
  9. backgroundColor(‘#75878a’)是为了让输入框的背景色为灰色。
  10. button_Item组件是用来放置按钮的。
  11. 在button_Item组件中,我们使用了@link装饰器来传递参数。

在textInput组件中,我们使用了@State装饰器来控制输入框的内容。对于textInput组件,我们使用了以下设置:

  1. textOverflow(100)是为了让输入框的内容超出部分不显示。
  2. copyOption(CopyOptions.None)是为了禁止复制输入框的内容。
  3. minFontSize(5)是为了让输入框的最小字体大小为5。
  4. maxFontSize(this.fontTitleSize)是为了让输入框的最大字体大小为我们定义的变量。
  5. textAlign(TextAlign.End)是为了让输入框的内容向右对齐。
  6. backgroundColor(‘#75878a’)是为了让输入框的背景色为灰色。

button_Item组件

import { trustedAppService } from "@kit.DeviceSecurityKit";

/**
* @program: 
*
* @description: 
*
* @author: 槐月
*
* @create: 2025/4/9-21:11
**/
@Extend(Button) function ButtonStatus(){
  .fontSize(20)
  .width('23%')
  .height('10%')
  .border({
    width:1,
    color:Color.Black
  })
  .type(ButtonType.Normal)
  .borderRadius(5)
  .margin({
    top:3,
    right:3,
    left:3,
    bottom:3
  })
}

@Component
export  struct button_Item {
  //字体
  @Link fontTopItem:number;
  //字体
  @Link fontEndItem:number;
  //内容
  @Link currentInput:string ;
  //内容
  @Link previousValueString:string;
  //控制
  @State hasNewNumber :boolean  =  true;
  //控制输入
  @State againInput:boolean = true;

  //对数据进行操作
  onClickButton(data:string){
    switch (data) {
      case 'C':
        this.currentInput = '0';
        this.previousValueString='';
        this.ConvertFontSize(data)
        break;
      case 'DEL':
        if (this.currentInput.length > 1) {
          this.currentInput = this.currentInput.slice(0, -1);
        } else {
          this.currentInput = '0';

        }
        this.ConvertFontSize(data)
        break;

      case '=':
        this.ConvertFontSize(data);
        this.StringIntoArray();
        this.againInput = false;
        break;

      default:
        if (this.currentInput.length === 1 && this.currentInput.toString() === "0") {
          this.currentInput = '';

        }
        if (!this.againInput) {
          this.currentInput = '';
          this.previousValueString = '';
          this.againInput = true;
        }

        this.currentInput += data;
        this.ConvertFontSize(data)
    }
  }
  //拆解字符串
  StringIntoArray(){
    let    charArray = this.currentInput.split("");
    //结果
    let result1  = '';
    let result2  ='';
    let sum=  0;

    charArray.forEach((value,index,array)=>{
      //中缀转后缀
      try {
        switch (value){
          case 'x':
            for (let i = 0; i < index; i++) {
              result1+=array[i];
            }
            for (let j =index+1 ; j < array.length; j++) {
              result2+=array[j];

            }
              sum = Number(result1)*Number(result2);
            break;
          case '/':
            for (let i = 0; i < index; i++) {
              result1+=array[i];
            }
            for (let j =index+1 ; j < array.length; j++) {
              result2+=array[j];

            }
            sum = Number(result1)/Number(result2);
            break;
          case '-':
            for (let i = 0; i < index; i++) {
              result1+=array[i];
            }
            for (let j =index+1 ; j < array.length; j++) {
              result2+=array[j];

            }
            sum = Number(result1)-Number(result2);
            break;
          case '+':
            for (let i = 0; i < index; i++) {
              result1+=array[i];
            }
            for (let j =index+1 ; j < array.length; j++) {
              result2+=array[j];

            }
            sum = Number(result1)+Number(result2);
            break;
        }
      }catch (e) {

      }
    })
    this.previousValueString = sum.toString();
    console.info(`${sum}`);

  }
  //大小写转换
  ConvertFontSize(data:string){
    switch (data){
      case '=':
        if(this.hasNewNumber){
          let Temp = this.fontTopItem;
          this.fontTopItem  = this.fontEndItem;
          this.fontEndItem = Temp;
          this.hasNewNumber=false;
        }
        break;

        default :
         if(!this.hasNewNumber){
           let Temp = this.fontTopItem;
           this.fontTopItem  = this.fontEndItem;
           this.fontEndItem = Temp;
           this.hasNewNumber  = true;
         }
    }
  }
  build() {
    Column(){
        Row(){
          //清除键位
          Button('C')
            .fontColor('#ee7800')
            .backgroundColor('#75878a')
          .ButtonStatus()
            .onClick(()=>{
              this.onClickButton('C')
            })
          //删除
          Button('DEL')
            .fontColor(Color.Black)
            .backgroundColor('#75878a')
            .ButtonStatus()
            .onClick(()=>{
              this.onClickButton('DEL');
            })
          Button('/')
            .fontColor(Color.Black)
            .backgroundColor('#75878a')
            .ButtonStatus()
            .onClick(()=>{
              this.onClickButton('/')

             // this.currentInput = this.computerResult.toString();
            })
          Button('x')
            .fontColor(Color.Black)
            .backgroundColor('#75878a')
            .ButtonStatus()
            .onClick(()=>{
              this.onClickButton('x')
            })
        }
        .justifyContent(FlexAlign.SpaceAround)

      Row(){
        Button('7')
          .fontColor(Color.Black)
          .backgroundColor('#f3f3f3')
          .ButtonStatus()
          .onClick(()=>{
              this.onClickButton('7')
          })
        Button('8')
          .fontColor(Color.Black)
          .backgroundColor('#f3f3f3')
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('8')
          })
        Button('9')
          .fontColor(Color.Black)
          .backgroundColor('#f3f3f3')
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('9')
          })
        Button('-')
          .fontColor(Color.Black)
          .backgroundColor('#75878a')
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('-')
          })

      }
      .justifyContent(FlexAlign.SpaceAround)

      Row(){
        Button('4')
          .fontColor(Color.Black)
          .backgroundColor('#f3f3f3')
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('4')
          })
        Button('5')
          .fontColor(Color.Black)
          .backgroundColor('#f3f3f3')
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('5')
          })
        Button('6')
          .fontColor(Color.Black)
          .backgroundColor('#f3f3f3')
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('6')
          })
        Button('+')
          .backgroundColor('#75878a')
          .fontColor(Color.Black)
          .ButtonStatus()
          .onClick(()=>{
            this.onClickButton('+')
          })
      }
      .justifyContent(FlexAlign.SpaceAround)

      Row(){
        Column(){
          Row(){
            Button('1')
              .fontSize(20)
              .border({
                width:1,
                color:Color.Black
              })
              .fontColor(Color.Black)
              .backgroundColor('#f3f3f3')
              .width('30%')
              .height('10%')
              .type(ButtonType.Normal)
              .borderRadius(5)
              .margin({
                top:3,
                right:3,
                left:3
              })
              .onClick(()=>{
                this.onClickButton('1')
              })
            Button('2')
              .fontSize(20)
              .border({
                width:1,
                color:Color.Black
              })
              .fontColor(Color.Black)
              .backgroundColor('#f3f3f3')
              .width('30%')
              .height('10%')
              .type(ButtonType.Normal)
              .borderRadius(5)
              .margin({
                top:3,
                right:3,
                left:3
              })
              .onClick(()=>{
                this.onClickButton('2')
              })
            Button('3')
              .fontSize(20)
              .border({
                width:1,
                color:Color.Black
              })
              .fontColor(Color.Black)
              .backgroundColor('#f3f3f3')
              .width('30%')
              .height('10%')
              .type(ButtonType.Normal)
              .borderRadius(5)
              .margin({
                top:3,
                right:3,
                left:3
              })
              .onClick(()=>{
                this.onClickButton('3')
              })
          }
          .justifyContent(FlexAlign.SpaceAround)

          Row(){
            Button('0')
              .fontSize(20)
              .border({
                width:1,
                color:Color.Black
              })
              .fontColor(Color.Black)
              .backgroundColor('#f3f3f3')
              .width('63%')
              .height('10%')
              .type(ButtonType.Normal)
              .borderRadius(5)
              .margin({
                top:3,
                right:3,
                left:3
              })
              .onClick(()=>{
                this.onClickButton('0')
              })
            Button('.')
              .fontSize(20)
              .border({
                width:1,
                color:Color.Black
              })
              .fontColor(Color.Black)
              .backgroundColor('#f3f3f3')
              .width('30%')
              .height('10%')
              .type(ButtonType.Normal)
              .borderRadius(5) .margin({
              top:3,
              right:3,
              left:3
            })
              .onClick(()=>{
                this.onClickButton('.')

              })
          }

        }
        .width('76%')
        Button('=')
          .fontSize(20)
          .backgroundColor('#ee7800')
          .width('22.5%')
          .height('20%')
          .borderRadius(5)
          .type(ButtonType.Normal)
          .margin({
            top:3,
            left:0,
            right:3
          })
          .onClick(()=>{
            this.onClickButton('=')
          })
      }
      .width('100%')
    }
    .width('90%')
  }
}

在这个代码片段中,我使用了Button()方法来创建按钮,并为每个按钮设置了不同的样式和事件处理函数。例如,我为数字按钮设置了一个点击事件处理器来更新计算器的输入值,为操作符按钮(如加号、减号等)也设置了相应的事件处理器,并为等号按钮设置了计算结果的事件处理器:

  1. onClickButton方法用于处理按钮点击事件,根据不同的操作更新计算器的状态。例如,当用户点击数字或运算符时,该方法会被调用以更新当前输入的表达式和显示的结果。
  2. StringIntoArray方法用于将字符串表达式拆分为数组,以便于后续的计算处理。例如,当用户点击等号时,该方法会被调用以解析输入的数学表达式并计算结果。
  3. ConvertFontSize方法用于根据屏幕宽度动态调整字体大小,以适应不同设备的显示需求。例如,在计算器界面中,该方法可以根据设备屏幕的尺寸来调整按钮和文本的大小,确保用户在不同大小的屏幕上都能舒适地使用应用。

这样一来,用户就可以通过点击按钮来输入数学表达式并得到计算结果了。例如,当用户在屏幕上依次点击数字7、加号(+)、数字5和等号(=)时,应用会显示12的结果。

最终,这段代码实现了基本的计算器功能,用户可以通过点击按钮来输入数学表达式并得到结果。

我已经把源码上传到Gitee仓库了,搜索harmony-os-calculator,即可找到。

臭宝们,快来试试看这个计算器吧!😄

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2332963.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring MVC 国际化机制详解(MessageSource 接口体系)

Spring MVC 国际化机制详解&#xff08;MessageSource 接口体系&#xff09; 1. 核心接口与实现类详解 接口/类名描述功能特性适用场景MessageSource核心接口&#xff0c;定义消息解析能力支持参数化消息&#xff08;如{0}占位符&#xff09;所有国际化场景的基础接口Resource…

文件IO5(JPEG图像原理与应用)

JPEG图像原理与应用 ⦁ 基本概念 JPEG&#xff08;Joint Photographic Experts Group&#xff09;指的是联合图像专家组&#xff0c;是国际标准化组织ISO制订并于1992年发布的一种面向连续色调静止图像的压缩编码标准&#xff0c;所以也被称为JPEG标准。 同样&#xff0c;JP…

P8682 [蓝桥杯 2019 省 B] 等差数列

题目描述 思路 让求包含这n个整数的最短等差数列&#xff0c;既让包含这几个数&#xff0c;项数最少&#xff0c;若项数最少&#xff0c;肯定不能添加小于最小的和大于最大的&#xff0c;而且让项数最小&#xff0c;公差得大 等差数列的公差aj - ai / j - i; 这又是一个等差数…

批量给文件编排序号,支持数字序号及时间日期序号编排文件

当我们需要对文件进行编号的时候&#xff0c;我们可以通过这个工具来帮我们完成&#xff0c;它可以支持从 001 到 100 甚至更多的数字序号编号。也可以支持按照日期、时间等方式对文件进行编号操作。这是一种操作简单&#xff0c;处理起来也非常的高效文件编排序号的方法。 工作…

Dynamics365 ExportPdfTemplateExportWordTemplate两个Action调用的body构造

这两天在用ExportPdfTemplate做pdf导出功能时&#xff0c;遇到了如下问题InnerException : Microsoft.OData.ODataException: An unexpected StartArray node was found when reading from the JSON reader. A PrimitiveValue node was expected. 我的场景是使用power automate…

国际物流怎么找客户?选择适合自己的企业拓客平台

在国际物流行业&#xff0c;获客一直是企业发展的核心难题。无论是跨境电商、传统外贸&#xff0c;还是国际货代&#xff0c;找到精准的客户资源并高效转化&#xff0c;是决定企业能否抢占市场蓝海的关键。今天&#xff0c;我们就来聊聊如何选择一个真正适合的国际物流拓客平台…

高效查询Redis中大数据的实践与优化指南

个人名片 &#x1f393;作者简介&#xff1a;java领域优质创作者 &#x1f310;个人主页&#xff1a;码农阿豪 &#x1f4de;工作室&#xff1a;新空间代码工作室&#xff08;提供各种软件服务) &#x1f48c;个人邮箱&#xff1a;[2435024119qq.com] &#x1f4f1;个人微信&a…

操作系统 4.2-键盘

键盘中断初始化和处理 提取的代码如下&#xff1a; // con_init 函数&#xff0c;初始化控制台&#xff08;包括键盘&#xff09;的中断 void con_init(void) {set_trap_gate(0x21, &keyboard_interrupt); } ​ // 键盘中断处理函数 .globl _keyboard_interrupt _keyboard…

STM32+EC600E 4G模块 与华为云平台通信

前言 由于在STM32巡回研讨会上淘了一块EC600E4G模块以及刚办完电信卡多了两张副卡&#xff0c;副卡有流量刚好可以用一下&#xff0c;试想着以后画一块ESP32板子搭配这个4G模块做个随身WIFI&#xff0c;目前先用这个模块搭配STM32玩一下云平顺便记录一下。 实验目的 实现STM…

进行性核上性麻痹患者,饮食 “稳” 健康

进行性核上性麻痹作为一种复杂且罕见的神经系统退行性疾病&#xff0c;给患者的身体机能和日常生活带来严重挑战。在积极接受专业治疗的同时&#xff0c;合理的饮食安排对于维持患者营养状况、缓解症状及提升生活质量起着关键作用。以下为患者提供一些健康饮食建议。 首先&…

【数据结构 · 初阶】- 顺序表

目录 一、线性表 二、顺序表 1.实现动态顺序表 SeqList.h SeqList.c Test.c 问题 经验&#xff1a;free 出问题&#xff0c;2种可能性 解决问题 &#xff08;2&#xff09;尾删 &#xff08;3&#xff09;头插&#xff0c;头删 &#xff08;4&#xff09;在 pos 位…

NHANES指标推荐:aMED

文章题目&#xff1a;The moderating effect of alternate Mediterranean diet on the association between sedentary behavior and insomnia in postmenopausal women DOI&#xff1a;10.3389/fnut.2024.1516334 中文标题&#xff1a;替代性地中海饮食对绝经后女性久坐行为与…

Spring Cloud 远程调用

4.OpenFeign的实现原理是什么&#xff1f; 在使用OpenFeign的时候&#xff0c;主要关心两个注解&#xff0c;EnableFeignClients和FeignClient。整体的流程分为以下几个部分&#xff1a; 启用Feign代理&#xff0c;通过在启动类上添加EnableFeignClients注解&#xff0c;开启F…

力扣 — — 最长公共子序列

力扣 — — 最长公共子序列 最长公共子序列 题源&#xff1a;1143. 最长公共子序列 - 力扣&#xff08;LeetCode&#xff09; 题目&#xff1a; 分析&#xff1a; 一道经典的题目&#xff1a;最长公共子序列(LCS) 题目大意&#xff1a;求两个字符串的最长公共序列。 算法&…

当一个 HTTP 请求发往 Kubernetes(K8s)部署的微服务时,整个过程流转时怎样的?

以下是一个简单的示意图来展示这个过程&#xff1a; 1. 请求发起 客户端&#xff08;可以是浏览器、移动应用或者其他服务&#xff09;发起一个 HTTP 请求到目标微服务的地址。这个地址可以是服务的域名、IP 地址或者 Kubernetes 服务的 ClusterIP、NodePort 等。 2. 外部流量…

蓝桥杯-蓝桥幼儿园(Java-并查集)

并查集的核心思想 并查集主要由两个操作构成&#xff1a; Find&#xff1a;查找某个元素所在集合的根节点。并查集的特点是&#xff0c;每个元素都指向它自己的父节点&#xff0c;根节点的父节点指向它自己。查找过程中可以通过路径压缩来加速后续的查找操作&#xff0c;即将路…

C++蓝桥杯填空题(攻克版)

片头 嗨~小伙伴们&#xff0c;咱们继续攻克填空题&#xff0c;先把5分拿到手~ 第1题 数位递增的数 这道题&#xff0c;需要我们计算在整数 1 至 n 中有多少个数位递增的数。 什么是数位递增的数呢&#xff1f;一个正整数如果任何一个数位不大于右边相邻的数位。比如&#xf…

JS 构造函数实现封装性

通过构造函数实现封装性&#xff0c;构造函数生成的对象独立存在互不影响 创建实例对象时&#xff0c;其中函数的创建会浪费内存

一站式云分账系统!智能虚拟户分账系统成电商合规“刚需”

电商智能分账解决&#xff1a;电商一站式破解多平台资金管理难题集中管理分账&#xff0c;分账后秒到&#xff0c;并为针对电商行业三大核心痛点提供高效应对策略&#xff1a; 1. 票据合规困境 智能对接上下游交易数据流&#xff0c;构建自动化票据协同机制&#xff0c;有效规…

数组 array

1、数组定义 是一种用于存储多个相同类型数据的存储模型。 2、数组格式 &#xff08;1&#xff09;数据类型[ ] 变量名&#xff08;比较常见这种格式&#xff09; 例如&#xff1a; int [ ] arr0&#xff0c;定义了一个int类型的数组&#xff0c;数组名是arr0&#xff1b; &am…