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

b23.gif

【引言】

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

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

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

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

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

? 開發(fā)語言:ArkTS

? 框架:ArkUI

? API版本:API 12

? 三方庫:@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)。通過 setValue 方法,可以設(shè)置溫度值并保留三位小數(shù)。

  1. 溫度單位類型枚舉

為了更好地管理和使用溫度單位,我們定義了一個(gè)溫度單位類型對象 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,來組織頁面的布局。頁面頂部有一個(gè)標(biāo)題 "溫度轉(zhuǎn)換",下方是一個(gè)垂直布局的容器,動態(tài)生成每個(gè)溫度單位的輸入框。每個(gè)輸入框都綁定了 onChange 事件,當(dāng)用戶輸入或更改溫度值時(shí),會觸發(fā)相應(yīng)的轉(zhuǎn)換邏輯,更新其他溫度單位的值。

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

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

例如,如果用戶在攝氏度輸入框中輸入溫度,程序會自動計(jì)算出華氏度、開爾文、蘭氏度和列氏度的值,并更新相應(yīng)的輸入框。

【用戶體驗(yàn)】

為了提升用戶體驗(yàn),我們在輸入框上添加了焦點(diǎn)狀態(tài)的處理。當(dāng)輸入框獲得焦點(diǎn)時(shí),背景顏色和邊框顏色會發(fā)生變化,以提示用戶當(dāng)前的操作位置。此外,輸入框還支持輸入過濾,只允許輸入數(shù)字和小數(shù)點(diǎn),確保輸入的有效性。

【完整代碼】

導(dǎo)包

ohpm install @nutpi/temperature-converter

代碼

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

// 定義溫度單位類型對象,用于存儲各溫度單位的名稱
const TemperatureUnitType: object = Object({
  Celsius: '攝氏度', // 攝氏度
  Fahrenheit: '華氏度', // 華氏度
  Kelvin: '開爾文', // 開爾文
  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)前溫度值到控制臺
  }
}

// 定義溫度轉(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è)置文本對齊方式
        .backgroundColor(Color.White) // 設(shè)置背景顏色
        .shadow({ // 添加陰影效果
          radius: 2, // 陰影半徑
          color: this.secondaryColor, // 陰影顏色
          offsetX: 0, // X軸偏移量
          offsetY: 5 // Y軸偏移量
        });

      // 循環(huán)遍歷溫度單位數(shù)組,動態(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 ? `請輸入${unit.title}` : '' // 輸入框的占位符文本
              })
                .inputFilter('[0-9.-]', (e) => console.log(JSON.stringify(e))) // 過濾輸入內(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}沒有焦點(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è)置水平對齊方式
      .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)和開爾文(Kelvin)之間的無縫切換。無論是學(xué)術(shù)研究、日常應(yīng)用還是專業(yè)工作,都能為您提供精準(zhǔn)便捷的溫度換算服務(wù)。')
          .textAlign(TextAlign.JUSTIFY) // 設(shè)置文本對齊方式
          .fontSize(this.fontSizeSmall) // 設(shè)置字體大小
          .fontColor(this.primaryColor) // 設(shè)置字體顏色
          .margin({ top: `${this.basePadding / 2}lpx` }); // 設(shè)置外邊距
      }
      .alignItems(HorizontalAlign.Start) // 設(shè)置水平對齊方式
      .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)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容