鴻蒙NEXT開(kāi)發(fā)案例:溫度轉(zhuǎn)換

b23.gif

【引言】

溫度是日常生活中常見(jiàn)的物理量屿聋,但不同國(guó)家和地區(qū)可能使用不同的溫度單位咧欣,如攝氏度(Celsius)凡泣、華氏度(Fahrenheit)枉疼、開(kāi)爾文(Kelvin)、蘭氏度(Rankine)和列氏度(Reaumur)鞋拟。為了方便用戶在這些溫度單位之間進(jìn)行快速準(zhǔn)確的轉(zhuǎn)換骂维,我們開(kāi)發(fā)了一款溫度轉(zhuǎn)換工具。該工具支持五種溫度單位之間的相互轉(zhuǎn)換贺纲,旨在為用戶提供便捷的服務(wù)航闺。

【環(huán)境準(zhǔn)備】

? 操作系統(tǒng):Windows 10

? 開(kāi)發(fā)工具:DevEco Studio NEXT Beta1 Build Version: 5.0.3.806

? 目標(biāo)設(shè)備:華為Mate60 Pro

? 開(kāi)發(fā)語(yǔ)言:ArkTS

? 框架:ArkUI

? API版本:API 12

? 三方庫(kù):@nutpi/temperature-converter(核心算法)

【項(xiàng)目結(jié)構(gòu)】

項(xiàng)目的核心組件是 TemperatureConverterApp,它負(fù)責(zé)構(gòu)建整個(gè)應(yīng)用的用戶界面,并處理用戶輸入及溫度單位之間的轉(zhuǎn)換邏輯潦刃。

  1. 溫度單位類定義

我們定義了一個(gè)溫度單位類 TemperatureUnit侮措,用于封裝溫度單位的基本信息及其操作方法。每個(gè)溫度單位都有一個(gè)標(biāo)題乖杠、當(dāng)前溫度值和輸入框的焦點(diǎn)狀態(tài)分扎。通過(guò) setValue 方法,可以設(shè)置溫度值并保留三位小數(shù)胧洒。

  1. 溫度單位類型枚舉

為了更好地管理和使用溫度單位畏吓,我們定義了一個(gè)溫度單位類型對(duì)象 TemperatureUnitType,列出了五種溫度單位的名稱卫漫。

  1. 應(yīng)用程序主組件

TemperatureConverterApp 組件是整個(gè)應(yīng)用的入口菲饼,它定義了應(yīng)用的樣式屬性,并實(shí)現(xiàn)了UI的構(gòu)建邏輯列赎。組件中包含了多個(gè)狀態(tài)變量巴粪,用于設(shè)置應(yīng)用的顏色、字體大小等樣式粥谬。

在UI構(gòu)建邏輯中肛根,我們使用了鴻蒙NEXT提供的布局組件,如 Column 和 Row漏策,來(lái)組織頁(yè)面的布局派哲。頁(yè)面頂部有一個(gè)標(biāo)題 "溫度轉(zhuǎn)換"昧狮,下方是一個(gè)垂直布局的容器胯府,動(dòng)態(tài)生成每個(gè)溫度單位的輸入框珊燎。每個(gè)輸入框都綁定了 onChange 事件条篷,當(dāng)用戶輸入或更改溫度值時(shí),會(huì)觸發(fā)相應(yīng)的轉(zhuǎn)換邏輯企垦,更新其他溫度單位的值帖渠。

  1. 溫度轉(zhuǎn)換邏輯

溫度轉(zhuǎn)換邏輯通過(guò)調(diào)用 @nutpi/temperature-converter 庫(kù)中的方法實(shí)現(xiàn)桑涎。當(dāng)用戶在某個(gè)溫度單位的輸入框中輸入溫度后即硼,程序會(huì)根據(jù)當(dāng)前輸入的溫度單位逃片,調(diào)用相應(yīng)的轉(zhuǎn)換方法,計(jì)算出其他溫度單位對(duì)應(yīng)的值只酥,并更新界面上的顯示褥实。

例如,如果用戶在攝氏度輸入框中輸入溫度裂允,程序會(huì)自動(dòng)計(jì)算出華氏度损离、開(kāi)爾文、蘭氏度和列氏度的值绝编,并更新相應(yīng)的輸入框僻澎。

【用戶體驗(yàn)】

為了提升用戶體驗(yàn)貌踏,我們?cè)谳斎肟蛏咸砑恿私裹c(diǎn)狀態(tài)的處理。當(dāng)輸入框獲得焦點(diǎn)時(shí)窟勃,背景顏色和邊框顏色會(huì)發(fā)生變化祖乳,以提示用戶當(dāng)前的操作位置。此外拳恋,輸入框還支持輸入過(guò)濾,只允許輸入數(shù)字和小數(shù)點(diǎn)砸捏,確保輸入的有效性谬运。

【完整代碼】

導(dǎo)包

ohpm install @nutpi/temperature-converter

代碼

// 引入溫度轉(zhuǎn)換器模塊
import { TemperatureConverter } from "@nutpi/temperature-converter"

// 定義溫度單位類型對(duì)象,用于存儲(chǔ)各溫度單位的名稱
const TemperatureUnitType: object = Object({
  Celsius: '攝氏度', // 攝氏度
  Fahrenheit: '華氏度', // 華氏度
  Kelvin: '開(kāi)爾文', // 開(kāi)爾文
  Rankine: '蘭氏度', // 蘭氏度
  Reaumur: '列氏度' // 列氏度
})

// 使用裝飾器定義一個(gè)溫度單位類
@ObservedV2
class TemperatureUnit {
  title: string // 溫度單位的標(biāo)題
  @Trace value: string = "" // 當(dāng)前溫度值垦藏,使用@Trace裝飾器追蹤變化
  @Trace isInputFocused: boolean = false // 輸入框是否獲得焦點(diǎn)梆暖,同樣使用@Trace追蹤變化

  // 構(gòu)造函數(shù),初始化時(shí)傳入溫度單位的標(biāo)題
  constructor(title: string) {
    this.title = title
  }

  // 設(shè)置溫度值的方法掂骏,保留三位小數(shù)
  setValue(value: number) {
    this.value = `${parseFloat(value.toFixed(3))}` // 將數(shù)值轉(zhuǎn)換成字符串轰驳,保留三位小數(shù)
    console.info(`溫度值:${this.value}`) // 打印當(dāng)前溫度值到控制臺(tái)
  }
}

// 定義溫度轉(zhuǎn)換器應(yīng)用程序的入口組件
@Entry
@Component
struct TemperatureConverterApp {
  // 定義一系列的狀態(tài)變量,用于設(shè)置應(yīng)用的顏色弟灼、字體大小等樣式
  @State private primaryColor: string = "#080808" // 主色調(diào)
  @State private secondaryColor: string = "#f7f7f7" // 次要色調(diào)
  @State private bgColor: string = "#f4f8fb" // 背景顏色
  @State private placeholderColor: string = "#2f9b6c" // 占位符顏色
  @State private textColor: string = "#a3a3a3" // 文本顏色
  @State private fontSizeSmall: number = 16 // 較小的字體大小
  @State private fontSizeLarge: number = 18 // 較大的字體大小
  @State private basePadding: number = 30 // 基礎(chǔ)內(nèi)邊距

  // 初始化溫度單位數(shù)組级解,創(chuàng)建每個(gè)溫度單位的實(shí)例
  @State private temperatureUnits: TemperatureUnit[] =
    Object.keys(TemperatureUnitType).map(unit => new TemperatureUnit(TemperatureUnitType[unit]))

  // 構(gòu)建應(yīng)用程序的UI
  build() {
    Column() { // 創(chuàng)建一個(gè)垂直布局容器
      // 添加標(biāo)題
      Text('溫度轉(zhuǎn)換')
        .fontColor(this.primaryColor) // 設(shè)置字體顏色
        .fontSize(this.fontSizeSmall) // 設(shè)置字體大小
        .width('100%') // 設(shè)置寬度
        .height(50) // 設(shè)置高度
        .textAlign(TextAlign.Center) // 設(shè)置文本對(duì)齊方式
        .backgroundColor(Color.White) // 設(shè)置背景顏色
        .shadow({ // 添加陰影效果
          radius: 2, // 陰影半徑
          color: this.secondaryColor, // 陰影顏色
          offsetX: 0, // X軸偏移量
          offsetY: 5 // Y軸偏移量
        });

      // 循環(huán)遍歷溫度單位數(shù)組,動(dòng)態(tài)生成每個(gè)溫度單位的輸入框
      Column() {
        ForEach(this.temperatureUnits, (unit: TemperatureUnit, index: number) => {
          Row() { // 創(chuàng)建一個(gè)水平布局容器
            // 顯示溫度單位的標(biāo)題
            Text(`${unit.title}`).fontSize(this.fontSizeSmall).fontColor(this.primaryColor)

            // 創(chuàng)建輸入框
            Row() {
              TextInput({
                text: unit.value, // 輸入框的初始值
                placeholder: !unit.isInputFocused ? `請(qǐng)輸入${unit.title}` : '' // 輸入框的占位符文本
              })
                .inputFilter('[0-9.-]', (e) => console.log(JSON.stringify(e))) // 過(guò)濾輸入內(nèi)容田绑,只允許數(shù)字和小數(shù)點(diǎn)
                .fontSize(this.fontSizeSmall) // 設(shè)置字體大小
                .backgroundColor(Color.Transparent) // 設(shè)置背景顏色
                .padding(0) // 設(shè)置內(nèi)邊距
                .width('100%') // 設(shè)置寬度
                .height('100%') // 設(shè)置高度
                .placeholderColor(unit.isInputFocused ? this.placeholderColor : this.textColor) // 設(shè)置占位符顏色
                .fontColor(unit.isInputFocused ? this.placeholderColor : this.primaryColor) // 設(shè)置字體顏色
                .caretColor(this.placeholderColor) // 設(shè)置光標(biāo)顏色
                .borderRadius(0) // 設(shè)置圓角
                .onBlur(() => unit.isInputFocused = false) // 失去焦點(diǎn)時(shí)的處理
                .onFocus(() => unit.isInputFocused = true) // 獲得焦點(diǎn)時(shí)的處理
                .onChange((value: string) => { // 輸入內(nèi)容改變時(shí)的處理
                  if (!unit.isInputFocused) { // 如果輸入框未獲得焦點(diǎn)勤哗,則不處理數(shù)據(jù)
                    console.info(`當(dāng)前位置${index}沒(méi)有焦點(diǎn),不處理數(shù)據(jù)內(nèi)容`)
                    return
                  }
                  if (unit.value == value) { // 如果新舊值相同掩驱,則不處理
                    console.info(`當(dāng)前位置${index}內(nèi)容與修改內(nèi)容相同芒划,不需要繼續(xù)處理`)
                    return
                  }
                  console.info(`onChange, unit.value:${unit.value}, value:${value}`) // 打印變更信息
                  const tempValue = Number(value); // 將輸入的字符串轉(zhuǎn)換成數(shù)字
                  unit.setValue(tempValue) // 更新當(dāng)前溫度單位的值

                  // 根據(jù)用戶輸入的溫度單位,計(jì)算并更新其他溫度單位的值
                  switch (index) {
                    case 0:
                      this.temperatureUnits[1].setValue(TemperatureConverter.celsiusToFahrenheit(tempValue))
                      this.temperatureUnits[2].setValue(TemperatureConverter.celsiusToKelvin(tempValue))
                      this.temperatureUnits[3].setValue(TemperatureConverter.celsiusToRankine(tempValue))
                      this.temperatureUnits[4].setValue(TemperatureConverter.celsiusToReaumur(tempValue))
                      break;
                    case 1:
                      this.temperatureUnits[0].setValue(TemperatureConverter.fahrenheitToCelsius(tempValue))
                      this.temperatureUnits[2].setValue(TemperatureConverter.fahrenheitToKelvin(tempValue))
                      this.temperatureUnits[3].setValue(TemperatureConverter.fahrenheitToRankine(tempValue))
                      this.temperatureUnits[4].setValue(TemperatureConverter.fahrenheitToReaumur(tempValue))
                      break;
                    case 2:
                      this.temperatureUnits[0].setValue(TemperatureConverter.kelvinToCelsius(tempValue))
                      this.temperatureUnits[1].setValue(TemperatureConverter.kelvinToFahrenheit(tempValue))
                      this.temperatureUnits[3].setValue(TemperatureConverter.kelvinToRankine(tempValue))
                      this.temperatureUnits[4].setValue(TemperatureConverter.kelvinToReaumur(tempValue))
                      break;
                    case 3:
                      this.temperatureUnits[0].setValue(TemperatureConverter.rankineToCelsius(tempValue))
                      this.temperatureUnits[1].setValue(TemperatureConverter.rankineToFahrenheit(tempValue))
                      this.temperatureUnits[2].setValue(TemperatureConverter.rankineToKelvin(tempValue))
                      this.temperatureUnits[4].setValue(TemperatureConverter.rankineToReaumur(tempValue))
                      break;
                    case 4:
                      this.temperatureUnits[0].setValue(TemperatureConverter.reaumurToCelsius(tempValue))
                      this.temperatureUnits[1].setValue(TemperatureConverter.reaumurToFahrenheit(tempValue))
                      this.temperatureUnits[2].setValue(TemperatureConverter.reaumurToKelvin(tempValue))
                      this.temperatureUnits[3].setValue(TemperatureConverter.reaumurToRankine(tempValue))
                      break;
                  }
                });
            }
            .padding(`${this.basePadding / 2}lpx`) // 設(shè)置內(nèi)邊距
            .backgroundColor(unit.isInputFocused ? this.bgColor : Color.Transparent) // 設(shè)置背景顏色
            .layoutWeight(1) // 設(shè)置布局權(quán)重
            .height(40) // 設(shè)置高度
            .borderWidth(1) // 設(shè)置邊框?qū)挾?            .borderRadius(10) // 設(shè)置圓角
            .borderColor(unit.isInputFocused ? this.placeholderColor : this.secondaryColor) // 設(shè)置邊框顏色
            .margin({ left: `${this.basePadding / 2}lpx`, right: `${this.basePadding / 2}lpx` }); // 設(shè)置外邊距
          }.margin({ top: `${this.basePadding / 2}lpx`, bottom: `${this.basePadding / 2}lpx` }); // 設(shè)置外邊距
        })
      }
      .alignItems(HorizontalAlign.Start) // 設(shè)置水平對(duì)齊方式
      .width('650lpx') // 設(shè)置寬度
      .padding(`${this.basePadding}lpx`) // 設(shè)置內(nèi)邊距
      .margin({ top: `${this.basePadding}lpx` }) // 設(shè)置外邊距
      .borderRadius(10) // 設(shè)置圓角
      .backgroundColor(Color.White) // 設(shè)置背景顏色
      .shadow({ // 添加陰影效果
        radius: 10, // 陰影半徑
        color: this.secondaryColor, // 陰影顏色
        offsetX: 0, // X軸偏移量
        offsetY: 0 // Y軸偏移量
      });

      // 添加工具介紹部分
      Column() {
        // 添加標(biāo)題
        Text('工具介紹').fontSize(this.fontSizeLarge).fontWeight(600).fontColor(this.primaryColor);

        // 添加工具介紹的文本
        Text('這款溫度單位轉(zhuǎn)換工具專為滿足您在科學(xué)研究欧穴、日常生活及工作中的需求而設(shè)計(jì)民逼。借助此工具,您可以輕松實(shí)現(xiàn)攝氏度(Celsius)涮帘、華氏度(Fahrenheit)和開(kāi)爾文(Kelvin)之間的無(wú)縫切換拼苍。無(wú)論是學(xué)術(shù)研究、日常應(yīng)用還是專業(yè)工作调缨,都能為您提供精準(zhǔn)便捷的溫度換算服務(wù)映屋。')
          .textAlign(TextAlign.JUSTIFY) // 設(shè)置文本對(duì)齊方式
          .fontSize(this.fontSizeSmall) // 設(shè)置字體大小
          .fontColor(this.primaryColor) // 設(shè)置字體顏色
          .margin({ top: `${this.basePadding / 2}lpx` }); // 設(shè)置外邊距
      }
      .alignItems(HorizontalAlign.Start) // 設(shè)置水平對(duì)齊方式
      .width('650lpx') // 設(shè)置寬度
      .padding(`${this.basePadding}lpx`) // 設(shè)置內(nèi)邊距
      .margin({ top: `${this.basePadding}lpx` }) // 設(shè)置外邊距
      .borderRadius(10) // 設(shè)置圓角
      .backgroundColor(Color.White) // 設(shè)置背景顏色
      .shadow({ // 添加陰影效果
        radius: 10, // 陰影半徑
        color: this.secondaryColor, // 陰影顏色
        offsetX: 0, // X軸偏移量
        offsetY: 0 // Y軸偏移量
      });
    }
    .height('100%') // 設(shè)置高度
    .width('100%') // 設(shè)置寬度
    .backgroundColor(this.bgColor); // 設(shè)置背景顏色
  }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市同蜻,隨后出現(xiàn)的幾起案子棚点,更是在濱河造成了極大的恐慌,老刑警劉巖湾蔓,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瘫析,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)贬循,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門咸包,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人杖虾,你說(shuō)我怎么就攤上這事烂瘫。” “怎么了奇适?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵坟比,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我嚷往,道長(zhǎng)葛账,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任皮仁,我火速辦了婚禮籍琳,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘贷祈。我一直安慰自己趋急,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布势誊。 她就那樣靜靜地躺著宣谈,像睡著了一般。 火紅的嫁衣襯著肌膚如雪键科。 梳的紋絲不亂的頭發(fā)上闻丑,一...
    開(kāi)封第一講書(shū)人閱讀 51,708評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音勋颖,去河邊找鬼嗦嗡。 笑死,一個(gè)胖子當(dāng)著我的面吹牛饭玲,可吹牛的內(nèi)容都是我干的侥祭。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼茄厘,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼矮冬!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起次哈,我...
    開(kāi)封第一講書(shū)人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤胎署,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后窑滞,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體琼牧,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡恢筝,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了巨坊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片撬槽。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖趾撵,靈堂內(nèi)的尸體忽然破棺而出侄柔,到底是詐尸還是另有隱情,我是刑警寧澤占调,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布暂题,位于F島的核電站,受9級(jí)特大地震影響妈候,放射性物質(zhì)發(fā)生泄漏敢靡。R本人自食惡果不足惜挂滓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一苦银、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧赶站,春花似錦幔虏、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至烙博,卻和暖如春瑟蜈,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背渣窜。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工铺根, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人乔宿。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓位迂,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親详瑞。 傳聞我的和親對(duì)象是個(gè)殘疾皇子掂林,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容