Android 小案例 -- 计算器

摘要:

计算器的界面分为两大部分,第一部分是上方的计算表达式,既包括用户的按键输入,也包括计算结果数字;第二部分是下方的各个按键,例如:从0到9的数字按钮、加减乘除与等号、正负号按钮、小数点按钮、求倒数按钮、开方按钮以及删除、清空、取消等控制按钮

分析:

  1. 线性布局LinearLayout:计算器的整体布局是从上到下排列着的

  2. 网格布局GridLayout:计算器下半部分的几排按钮,正好成五行四列表格分布,适合采用GridLayout

  3. 滚动视图ScrollView:计算器界面如果超出屏幕大小,就要支持滚动

  4. 文本视图TextView:计算结果文本需要使用TextView,且文字靠下靠右显示

  5. 按钮Button:用于0-9的数字按键,以及加减乘除等运算按键

  6. 图像按钮ImageButton:开根号的运算符虽然能够打出来,但是右上角少了一横,所以该按钮要用一张标准的开根号图片显示

效果:

常量文件

1、buttonstyle.xml

宽高常量

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="button_font_size">30sp</dimen>
    <dimen name="button_height">70dp</dimen>

</resources>

2、strings.xml

<resources>
    <string name="app_name">SimpleControl</string>
    <string name="hello">世界未来与你相伴!!!</string>
    <string name="simple_calculator">计算器</string>
    <string name="cancel">CE</string>
    <string name="divide">÷</string>
    <string name="multiply">×</string>
    <string name="clear">C</string>
    <string name="seven">7</string>
    <string name="eight">8</string>
    <string name="nine">9</string>
    <string name="add">+</string>
    <string name="four">4</string>
    <string name="five">5</string>
    <string name="six">6</string>
    <string name="minus">-</string>
    <string name="one">1</string>
    <string name="two">2</string>
    <string name="three">3</string>
    <string name="reciprocal">1/x</string>
    <string name="zero">0</string>
    <string name="dot">.</string>
    <string name="equal">=</string>

</resources>

3、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simplecontrol">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SimpleControl">
        <activity
            android:name=".CalculatorActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4、colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="xian_green">#058531</color>
    <color name="gray">#666666</color>
    <color name="yellow">#FFFF00</color>
    <color name="red">#FF0033</color>
    <color name="blue">#0066CC</color>
    <color name="green">#33CC33</color>
    
</resources>

5、themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.SimpleControl" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>

</resources>

布局文件

1、activity_calculator.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE"
    android:orientation="vertical"
    android:padding="5dp">

    <!--最外层的一个线性布局-->
    <!--垂直滚动页面-->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/simple_calculator"
                android:textColor="@color/green"
                android:textSize="50dp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="#CCCCCC"
                android:lines="1"
                />
            <TextView
                android:id="@+id/tv_result_calculator"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:gravity="bottom|right"
                android:lines="4"
                android:text="0"
                android:textColor="@color/black"
                android:textSize="25sp" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="#CCCCCC"
                android:lines="2"
                />
            <!--网格布局设置 5 * 4 每一个按钮功能不一样-->
            <GridLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:columnCount="4"
                android:rowCount="5">
                <Button
                    android:id="@+id/btn_cancel"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/cancel"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_divide"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/divide"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_multiply"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/multiply"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_clear"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/clear"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_seven"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/seven"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_eight"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/eight"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_nine"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/nine"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_add"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/add"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_four"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/four"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_five"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/five"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_six"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/six"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_minus"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/minus"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_one"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/one"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_two"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/two"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_three"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/three"
                    android:textSize="@dimen/button_font_size" />

                <ImageButton
                    android:id="@+id/btn_sqrt"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:scaleType="centerInside"
                    android:src="@drawable/sqrt">
                </ImageButton>
                <Button
                    android:id="@+id/btn_reciprocal"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/reciprocal"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_zero"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/zero"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_dot"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/dot"
                    android:textSize="@dimen/button_font_size" />

                <Button
                    android:id="@+id/btn_equal"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/button_height"
                    android:layout_columnWeight="1"
                    android:gravity="center"
                    android:text="@string/equal"
                    android:textSize="@dimen/button_font_size" />
            </GridLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

逻辑处理代码

1、Calculator.java

package com.example.simplecontrol;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Array;

public class CalculatorActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_result_calculator;

    //第一个操作数
    private String firstNum = "";

    //运算符
    private String operator = "";

    //第二个操作数
    private String secondNum = "";

    //当前计算结果
    private String result = "";

    //显示的文本内容
    private String showText = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator);
        //布局文件种获取tv_result_calculator文本视图
        tv_result_calculator = findViewById(R.id.tv_result_calculator);

        //下面给每个按钮控件都注册了点击监听器
        findViewById(R.id.btn_cancel).setOnClickListener(this);
        //"除法"按钮
        findViewById(R.id.btn_divide).setOnClickListener(this);
        //"乘法”按钮
        findViewById(R.id.btn_multiply).setOnClickListener(this);
        //"清除" 按钮
        findViewById(R.id.btn_clear).setOnClickListener(this);
        //1 数字7
        findViewById(R.id.btn_seven).setOnClickListener(this);
        //数字8
        findViewById(R.id.btn_eight).setOnClickListener(this);
        //数字9
        findViewById(R.id.btn_nine).setOnClickListener(this);
        //"加法"按钮
        findViewById(R.id.btn_add).setOnClickListener(this);
        //数字4
        findViewById(R.id.btn_four).setOnClickListener(this);
        //数字5
        findViewById(R.id.btn_five).setOnClickListener(this);
        //数字6
        findViewById(R.id.btn_six).setOnClickListener(this);
        //"减法"
        findViewById(R.id.btn_minus).setOnClickListener(this);
        //数字1按钮
        findViewById(R.id.btn_one).setOnClickListener(this);
        //数字2
        findViewById(R.id.btn_two).setOnClickListener(this);
        //数字3
        findViewById(R.id.btn_three).setOnClickListener(this);
        //求倒数按钮
        findViewById(R.id.btn_reciprocal).setOnClickListener(this);
        //数字0
        findViewById(R.id.btn_zero).setOnClickListener(this);
        //"小数点" 按钮
        findViewById(R.id.btn_dot).setOnClickListener(this);
        // "等号"按钮
        findViewById(R.id.btn_equal).setOnClickListener(this);
        // "开平方"按钮
        findViewById(R.id.btn_sqrt).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        String inputText;
        //如果是根号按钮
        if (v.getId() == R.id.btn_sqrt) {
            inputText = "√";

        } else {
            //其他的按钮 转换成文本内容
            inputText = ((TextView) v).getText().toString();
        }
        switch (v.getId()) {
            //清除按钮
            case R.id.btn_clear:
                clear();
                refreshText("0");
                break;
            //取消按钮
            case R.id.btn_cancel:
                if (operator.equals("")) {
                    if (firstNum.length() == 1) {
                        firstNum = "0";
                    } else if (firstNum.length() > 1) {
                        firstNum = firstNum.substring(0, firstNum.length() - 1);
                    } else {
                        Toast.makeText(this, "0", Toast.LENGTH_SHORT).show();
                    }
                    showText = firstNum;
                    refreshText(showText);
                }else if(!operator.equals("") ){
                    if(secondNum.length() == 1){
                        secondNum = "";
                    }else if(secondNum.length() > 1){
                        secondNum = secondNum.substring(0,secondNum.length()-1);
                    }else if(secondNum.length() == 0){
                        Toast.makeText(this,"0",Toast.LENGTH_SHORT).show();
                    }
                    showText = showText.substring(0,showText.length()-1);
                    refreshText(showText);
                }
                break;
            //加、减、乘、除按钮
            case R.id.btn_add:
            case R.id.btn_minus:
            case R.id.btn_multiply:
            case R.id.btn_divide:
                //运算符
                operator = inputText;
                refreshText(showText + operator);
                break;

            //等号按钮
            case R.id.btn_equal:
                // 加减乘除进行四则运算
                double calculate_result = calculateFour();
                refreshOperate(String.valueOf(calculate_result));
                refreshText(showText + "=" + result);
                break;
            //开根号按钮
            case R.id.btn_sqrt:

                double sqrt_result = Math.sqrt(Double.parseDouble(firstNum));
                refreshOperate(String.valueOf(sqrt_result));
                refreshText(showText + "√=" + result);
                break;
            //求倒数按钮
            case R.id.btn_reciprocal:
                double reciprocal = 1.0 / Double.parseDouble(firstNum);
                refreshOperate(String.valueOf(reciprocal));
                refreshText(showText + "/=" + result);
                break;

            //其他按钮,包括数字和小数点
            default:
                if (result.length() > 0 && operator.equals("")) {
                    clear();
                }
                // 判断是否为运算符
                if (operator.equals("")) {
                    //五运算符
                    firstNum = firstNum + inputText;

                } else {
                    //有算符
                    secondNum = secondNum + inputText;
                }
                //整数不需要前面的 0 和 .
                if (showText.equals("0") && inputText.equals(".")) {
                    //显示内容
                    refreshText(inputText);
                } else {
                    refreshText(showText + inputText);
                }
                break;
        }

    }

    //四则运算 ,返回结果
    private double calculateFour() {
        switch (operator) {
            case "+":
                return Double.parseDouble(firstNum) + Double.parseDouble(secondNum);
            case "-":
                return Double.parseDouble(firstNum) - Double.parseDouble(secondNum);
            case "×":
                return Double.parseDouble(firstNum) * Double.parseDouble(secondNum);
            default:
                return Double.parseDouble(firstNum) / Double.parseDouble(secondNum);
        }
    }

    //清空、并初始化
    private void clear() {
        refreshOperate("");
        refreshText("");
    }

    //刷新运算结果
    private void refreshOperate(String new_result) {
        result = new_result;
        //连续计算 下一次结果,就变成下一次计算的第一个数字
        firstNum = result;
        secondNum = "";
        operator = "";
    }

    //刷新显示文本
    public void refreshText(String text) {
        showText = text;
        tv_result_calculator.setText(showText);
    }
}

初学者。

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
好的,我很乐意为您介绍JavaScript实现房贷计算器的方法。 首先,我们需要了解房贷计算器的计算公式。一般来说,房贷计算器需要计算出每月还款金额、还款总额、支付利息总额等指标。这些指标的计算公式如下: 每月还款金额 = [贷款本金 × 月利率 × (1 + 月利率)^还款月数] ÷ [(1 + 月利率)^还款月数 - 1] 还款总额 = 每月还款金额 × 还款月数 支付利息总额 = 还款总额 - 贷款本金 了解了计算公式之后,我们就可以开始编写JavaScript代码了。以下是一个简单的房贷计算器实现代码示例: ```javascript // 获取页面元素 var loanAmount = document.getElementById("loan-amount"); var loanTerm = document.getElementById("loan-term"); var interestRate = document.getElementById("interest-rate"); var calculateButton = document.getElementById("calculate-button"); var resultMonthlyPayment = document.getElementById("result-monthly-payment"); var resultTotalPayment = document.getElementById("result-total-payment"); var resultTotalInterest = document.getElementById("result-total-interest"); // 计算每月还款金额 function calculateMonthlyPayment(loanAmount, loanTerm, interestRate) { var monthlyInterestRate = interestRate / 1200; // 月利率 var totalPayment = loanAmount * (1 + monthlyInterestRate * loanTerm); // 还款总额 var monthlyPayment = totalPayment / loanTerm; // 每月还款金额 return monthlyPayment.toFixed(2); // 保留两位小数 } // 计算房贷支付指标 function calculateLoanPayments() { var loanAmountValue = parseFloat(loanAmount.value); var loanTermValue = parseFloat(loanTerm.value); var interestRateValue = parseFloat(interestRate.value); var monthlyPayment = calculateMonthlyPayment(loanAmountValue, loanTermValue, interestRateValue); var totalPayment = monthlyPayment * loanTermValue; var totalInterest = totalPayment - loanAmountValue; resultMonthlyPayment.innerHTML = monthlyPayment.toFixed(2); resultTotalPayment.innerHTML = totalPayment.toFixed(2); resultTotalInterest.innerHTML = totalInterest.toFixed(2); } // 注册计算按钮点击事件 calculateButton.addEventListener("click", calculateLoanPayments); ``` 在上面的代码示例中,我们首先通过`document.getElementById()`方法获取了页面中的各个元素,然后定义了一个计算每月还款金额的函数`calculateMonthlyPayment()`,最后定义了一个计算房贷支付指标的函数`calculateLoanPayments()`。在`calculateLoanPayments()`函数中,我们获取了用户输入的贷款金额、贷款期限和利率,然后调用`calculateMonthlyPayment()`函数计算每月还款金额,并根据公式计算出还款总额和支付利息总额。最后,我们将计算结果显示到页面中相应的元素中。 最后,我们还为计算按钮注册了一个点击事件,当用户点击按钮时,会自动计算房贷支付指标并显示到页面上。 以上就是一个简单的房贷计算器JavaScript实现方法。希望可以帮助到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫十二懿

你的支持就是写文章的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值