首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 計算器 App 開發:GridLayout + ViewBinding 現代實現

     編輯:程式設計疑難解答

界面佈局

<LinearLayout xmlns:android="..."
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView android:id="@+id/tvResult" ... />
    <GridLayout
        android:id="@+id/gridKeys"
        android:columnCount="4"
        android:rowCount="5"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <!-- 按鈕由代碼動態添加或 XML 定義 -->
    </GridLayout>
</LinearLayout>

邏輯實現

  1. 維護 operand1, operator, waitingForOperand 狀態
  2. 數字鍵追加顯示;運算鍵觸發計算並更新狀態
  3. 等號鍵執行最終計算,顯示結果
  4. 使用 BigDecimal 避免浮點誤差

關鍵代碼

binding.gridKeys.setOnClickListener(v -> {
    String tag = (String) v.getTag();
    if ("0123456789.".contains(tag)) appendDigit(tag);
    else if ("+-*/".contains(tag)) setOperator(tag);
    else if ("=".equals(tag)) calculate();
    else if ("C".equals(tag)) clear();
});

進階功能

支持連續運算、括號、百分比、科學計算模式可擴展為表達式解析器(Shunting-yard 算法)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved