android计算器开源小项目代码(附安装包.apk)

最近在学习安卓开发,做了个小计算器作为实践。发现网上的计算器教程代码的健壮性不够好,只能够容忍正确的输入。于是我花了几天时间写了个完整的程序。可能是我水平有限,其中条件控制逻辑设计的比较复杂,但我受开源运动影响比较深,我学习了别人的代码,就应该把自己的代码公布出来,即使写的不好,多多少少能为一些人带来一点点帮助吧,同时记录自己的学习历程。

先来展示一下成果:

 

 开发工具我选择了android studio, 诚实的说我对xml并不是那么的了解,所以我只能采用所见即所得的办法,不过这个小项目做下来,感觉比刚开始好多了。

再说一下思路吧,计算器上方是个显示器,是一个TextView,显示器上方的东西是个spinner,作用待会再说,显示器下方都是button,通过监听button的摁下,在TextView上显示用户输入来与用户做交互,然后将TextView上的内容提取出来做运算,再显示再屏幕上。其实大部分的工作都是在做人机交互以及规范用户的输入,真正实现功能的代码并不多。

下面开始贴代码了,先贴xml吧,方便与上面的图片比对

 

xml代码部分(AndroidMainfest.xml):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

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

            <Spinner
                android:id="@+id/spinner"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="start"
                android:textSize="50sp" />

            <TextView
                android:id="@+id/concle"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="bottom|end"
                android:maxLines="2"
                android:minLines="1"
                android:singleLine="false"
                android:text="@string/priNum"
                android:textSize="45sp"
                />

        </LinearLayout>

        <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="4"
            android:gravity="bottom">

            <TableRow
                android:id="@+id/line1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <Button
                    android:id="@+id/buttonClean"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@android:color/darker_gray"
                    android:text="@string/button_c"
                    android:textColor="@android:color/holo_red_dark"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonMul"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#fa8e12"
                    android:text="@string/button_mul"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonDiv"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#fa8e12"
                    android:text="@string/button_div"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonDel"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#b22222"
                    android:text="@string/button_del"
                    android:textSize="40sp" />
            </TableRow>

            <TableRow
                android:id="@+id/line2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <Button
                    android:id="@+id/button7"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_7"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/button8"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_8"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/button9"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_9"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonAdd"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#fa8e12"
                    android:text="@string/button_add"
                    android:textSize="40sp" />
            </TableRow>

            <TableRow
                android:id="@+id/line3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <Button
                    android:id="@+id/button4"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_4"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/button5"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_5"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/button6"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_6"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonSub"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#fa8e12"
                    android:text="@string/button_sub"
                    android:textSize="40sp" />
            </TableRow>

            <TableRow
                android:id="@+id/line4"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <Button
                    android:id="@+id/button1"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_1"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/button2"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_2"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/button3"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_3"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonList"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:autoText="false"
                    android:background="#FFdab9"
                    android:onClick="showDialog"
                    android:text="@string/button_list"
                    android:textSize="40sp" />
            </TableRow>

            <TableRow
                android:id="@+id/line5"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <Button
                    android:id="@+id/button0"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#cdced1"
                    android:text="@string/button_0"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonPoint"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#ff6347"
                    android:text="@string/button_point"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonCopyright"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#696969"
                    android:text="@string/button_copyright"
                    android:textColor="#800000"
                    android:textSize="40sp" />

                <Button
                    android:id="@+id/buttonEqual"
                    style="?android:attr/buttonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#fa8e12"
                    android:text="@string/button_equal"
                    android:textSize="40sp" />
            </TableRow>

        </TableLayout>

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

代码比较长,我学习xml的时候也挺苦恼的,不过还是耐心的看一下吧,多看几个就没那么陌生了。

 

接下来是java的代码(MainActivity.java)  注释加在文本的后面:

其中定义了

caculate()          // 实现计算功能的函数

setprecision(String s)        //  

showDialog()

showDevDialog()  四个公有方法(不包括监听事件)

 

package com.era_huang;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // 定义所有按键
    Button button_0;
    Button button_1;
    Button button_2;
    Button button_3;
    Button button_4;
    Button button_5;
    Button button_6;
    Button button_7;
    Button button_8;
    Button button_9;
    Button button_point;
    Button button_add;
    Button button_sub;
    Button button_mul;
    Button button_div;
    Button button_del;
    Button button_c;
    Button button_equal;
    Button button_list;
    Button button_copyright;
    TextView terminal;  // 定义计算器显示屏
    boolean pointLock1 = false;     // 防止一个数中有多个小数点,摁下一个点后就锁住
    boolean pointLock2 = false;     // 防止在运算符后连接小数点
    boolean opraterLock = false;    // 防止两个数之间输入多于两个运算符
    Spinner spinner;      // 定义了显示屏上那个下拉菜单,用来自动保留小数位数
    List<String> list;    // spinner中的子选项
    ArrayAdapter<String> adapter;
    int reservedDecimalNumber = 4;   // 默认保留的小数位数为4位小数
    BigDecimal result = BigDecimal.valueOf(0);  // java中的大数值,为了实现精确的计算,因为这是一个计算器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 让各个button连接对应组件
        button_0 = findViewById(R.id.button0);
        button_1 = findViewById(R.id.button1);
        button_2 = findViewById(R.id.button2);
        button_3 = findViewById(R.id.button3);
        button_4 = findViewById(R.id.button4);
        button_5 = findViewById(R.id.button5);
        button_6 = findViewById(R.id.button6);
        button_7 = findViewById(R.id.button7);
        button_8 = findViewById(R.id.button8);
        button_9 = findViewById(R.id.button9);
        button_point = findViewById(R.id.buttonPoint);
        button_equal = findViewById(R.id.buttonEqual);
        button_add = findViewById(R.id.buttonAdd);
        button_sub = findViewById(R.id.buttonSub);
        button_c = findViewById(R.id.buttonClean);
        button_mul = findViewById(R.id.buttonMul);
        button_div = findViewById(R.id.buttonDiv);
        button_del = findViewById(R.id.buttonDel);
        button_list = findViewById(R.id.buttonList);
        button_copyright = findViewById(R.id.buttonCopyright);

        terminal = findViewById(R.id.concle);
        // 创建显示屏上的下拉菜单
        spinner = findViewById(R.id.spinner);
        list = new ArrayList<>();

        list.add("4位小数");
        list.add("0位小数");
        list.add("1位小数");
        list.add("2位小数");
        list.add("6位小数");
        list.add("8位小数");
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
        spinner.setAdapter(adapter);

        //监听spinner
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String info = adapter.getItem(position);
                setprecision(info);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        // 监听各个按钮
        button_0.setOnClickListener(this);
        button_1.setOnClickListener(this);
        button_2.setOnClickListener(this);
        button_3.setOnClickListener(this);
        button_4.setOnClickListener(this);
        button_5.setOnClickListener(this);
        button_6.setOnClickListener(this);
        button_7.setOnClickListener(this);
        button_8.setOnClickListener(this);
        button_9.setOnClickListener(this);
        button_point.setOnClickListener(this);
        button_equal.setOnClickListener(this);
        button_add.setOnClickListener(this);
        button_sub.setOnClickListener(this);
        button_c.setOnClickListener(this);
        button_mul.setOnClickListener(this);
        button_div.setOnClickListener(this);
        button_del.setOnClickListener(this);
        button_list.setOnClickListener(this);
        button_copyright.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 按键按下阴影动画
        Animation alphaAnimation = new AlphaAnimation(0.1f, 0);
        alphaAnimation.setInterpolator(new LinearInterpolator());
        alphaAnimation.setDuration(100);
        alphaAnimation.setRepeatCount(1);
        alphaAnimation.setRepeatMode(Animation.REVERSE);
        v.startAnimation(alphaAnimation);

        // 获取显示器上的字符串
        String str = terminal.getText().toString();


        //判断那个键被按下
        switch (v.getId()) {
            // 数值类按键
            case R.id.button0:
            case R.id.button1:
            case R.id.button2:
            case R.id.button3:
            case R.id.button4:
            case R.id.button5:
            case R.id.button6:
            case R.id.button7:
            case R.id.button8:
            case R.id.button9:
                //如果显示器上显示错误,摁下任意数字键归零
                if (str.equals("错误"))
                    terminal.setText("0");
                //当有数字被按下,就不存在运算符连接point(小数点)的情况,锁2打开
                pointLock2 = false;
                opraterLock = false;
                String text1;

                // 显示屏默认为0,如果为0显示button对应的值,
                // 如果不为0,显示屏上的字符串与摁下的字符串连接
                if (str.equals("0")) {
                    text1 = "" + ((Button) v).getText();
                } else {
                    text1 = str + ((Button) v).getText();
                }
                terminal.setText(text1);
                break;
            //小数点摁键,如果两个锁都打开,就可以摁下小数点
            case R.id.buttonPoint:
                if (!pointLock1 && !pointLock2) {
                    String text2 = str + ((Button) v).getText();
                    terminal.setText(text2);
                    pointLock1 = true;
                }
                break;

            // 运算符按键,如果摁下,运算符后的为另一个数字,则可以打下一个小数点
            //所以锁1打开。而运算符后不能接小数点,所以锁2锁上,等打数字后,锁2解开
            case R.id.buttonAdd:
            case R.id.buttonSub:
            case R.id.buttonMul:
            case R.id.buttonDiv:

                //如果前一位不为小数点才能摁下运算符按键
                if (str.charAt(str.length() - 1) != '.' && !opraterLock) {
                    pointLock1 = false;
                    pointLock2 = true;
                    opraterLock = true;
                    String text3 = str + ((Button) v).getText();
                    terminal.setText(text3);
                }
                break;

            //删除键
            case R.id.buttonDel:
                //当小数点被删除后,锁1要打开,不然无法再次输入小数点,
                // 因为锁1只有在摁下运算符后才会打开
                if (str.charAt(str.length() - 1) == '.') {
                    pointLock1 = false;
                    pointLock2 = false;
                }
                //如果运算符被删掉,opraterLock打开,能够再次输入运算符
                //pointLock1要锁上,以免在输入运算符再将其删除后,输入一个数字即又可以输入point的情况
                if (str.charAt(str.length() - 1) == '+' || str.charAt(str.length() - 1) == '-' ||
                        str.charAt(str.length() - 1) == '*' || str.charAt(str.length() - 1) == '/') {
                    opraterLock = false;
                    pointLock1 = true;
                }

                //如果长度大于一,返回去掉最后一个字符的字符串
                if (str.length() > 1) {
                    str = str.substring(0, str.length() - 1);

                }
                //否则(即长度为1时直接设置显示器中为0)
                else {
                    str = "0";
                }

                terminal.setText(str);
                break;

            //清屏操作所有锁都打开
            case R.id.buttonClean:
                str = "0";
                terminal.setText(str);
                pointLock1 = false;
                pointLock2 = false;
                opraterLock = false;
                break;
            //求运算结果
            case R.id.buttonEqual:
                char lastChar = str.charAt(str.length() - 1);
                if (lastChar != '.' && lastChar != '+' && lastChar != '-'
                        && lastChar != '*' && lastChar != '/') {
                    try {
                        caculate();
                    } catch (Exception e) {
                        str = "错误";
                        terminal.setText(str);
                    }
                }
                break;
            case R.id.buttonList:
                showDialog();
                break;
            case R.id.buttonCopyright:
                showDevDialog();
                break;
        }
    }


    public void caculate() {
        String expression = terminal.getText().toString();
        // 利用正则表达式将各个数值分开,提取到数组里
        String[] expArr = expression.split("\\+|\\-|\\*|\\/");
        String[] operate = expression.split("\\d+|\\.");
        String[] foperate = new String[100];
        double[] numArr = new double[expArr.length];
        int index = 0, index1;
        double sum = 0;

        if (expression.charAt(0) == '-') {
            index1 = 1;
        } else {
            index1 = 0;
        }

        for (; index1 < expArr.length; index1++) {

            numArr[index1] = Double.parseDouble(expArr[index1]);
        }


        for (String mystr : operate) {
            if ((!mystr.equals("")) && (!mystr.equals(null))) {
                foperate[index] = mystr;
            }
            index++;
        }


        index = 0;
        for (String operater : foperate) {
            if (operater != null) {
                if (operater.equals("-")) {
                    numArr[index + 1] = -numArr[index + 1];
                }
                index++;
            }
        }


        index = 0;
        for (int i = 0; i < foperate.length; i++) {
            if (foperate[i] != null) {
                if (foperate[i].equals("*")) {
                    numArr[index + 1] = numArr[index] * numArr[index + 1];
                    numArr[index] = 0;
                    foperate[i] = null;
                } else if (foperate[i].equals("/")) {
                    numArr[index + 1] = numArr[index] / numArr[index + 1];
                    numArr[index] = 0;
                    foperate[i] = null;
                }
                index++;
            }
        }

        for (Double d : numArr) {
            sum += d;
        }
        BigDecimal accurateSum = BigDecimal.valueOf(sum).setScale(reservedDecimalNumber, BigDecimal.ROUND_HALF_UP);
        result = accurateSum;
        terminal.setText(String.valueOf(accurateSum));
    }

    public void setprecision(String s) {
        String formatS = s.substring(0, 1);
        reservedDecimalNumber = Integer.valueOf(formatS);
        if (!result.equals(BigDecimal.valueOf(0))) {
            terminal.setText(String.valueOf(result.setScale(reservedDecimalNumber, BigDecimal.ROUND_HALF_UP)));
        }
    }

    // 消息提示框
    public void showDialog() {
        new AlertDialog.Builder(this)
                .setMessage("计算值记录功能将在下次重大改良中开发,感谢大家支持!")
                .setPositiveButton("确定", null)
                .show();

    }
    // 消息提示框
    public void showDevDialog() {
        new AlertDialog.Builder(this)
                .setMessage("开发者:Era_Huang\nQQ:1295289600\n倾尽所能为用户开发最优质的应用")
                .setPositiveButton("确定", null)
                .show();
    }
}

 

加注释真的加的心累,附上apk的度盘:

https://pan.baidu.com/s/1A1BwwzTvC6OCcrbpCap_lA

希望能和大家一起进步

 

 

  • 11
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是一个简易的计算器的实现,使用 Java 和 Android Studio: 布局文件 `activity_main.xml`: ```xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/result_textview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="0" android:textSize="32sp" android:textAlignment="center" android:padding="16dp" android:background="@android:color/darker_gray" android:textColor="@android:color/white"/> <GridLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/result_textview" android:columnCount="4" android:rowCount="5" android:padding="16dp"> <Button android:id="@+id/button_1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="1" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_2" android:layout_width="0dp" android:layout_height="wrap_content" android:text="2" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_3" android:layout_width="0dp" android:layout_height="wrap_content" android:text="3" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_divide" android:layout_width="0dp" android:layout_height="wrap_content" android:text="/" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_4" android:layout_width="0dp" android:layout_height="wrap_content" android:text="4" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_5" android:layout_width="0dp" android:layout_height="wrap_content" android:text="5" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_6" android:layout_width="0dp" android:layout_height="wrap_content" android:text="6" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_multiply" android:layout_width="0dp" android:layout_height="wrap_content" android:text="*" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_7" android:layout_width="0dp" android:layout_height="wrap_content" android:text="7" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_8" android:layout_width="0dp" android:layout_height="wrap_content" android:text="8" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_9" android:layout_width="0dp" android:layout_height="wrap_content" android:text="9" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_minus" android:layout_width="0dp" android:layout_height="wrap_content" android:text="-" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_clear" android:layout_width="0dp" android:layout_height="wrap_content" android:text="C" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_0" android:layout_width="0dp" android:layout_height="wrap_content" android:text="0" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_equal" android:layout_width="0dp" android:layout_height="wrap_content" android:text="=" android:textSize="24sp" android:layout_columnWeight="1"/> <Button android:id="@+id/button_plus" android:layout_width="0dp" android:layout_height="wrap_content" android:text="+" android:textSize="24sp" android:layout_columnWeight="1"/> </GridLayout> </RelativeLayout> ``` Java 代码 `MainActivity.java`: ```java import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView resultTextView; private String operand1; private String operator; private String operand2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); resultTextView = findViewById(R.id.result_textview); Button button1 = findViewById(R.id.button_1); Button button2 = findViewById(R.id.button_2); Button button3 = findViewById(R.id.button_3); Button button4 = findViewById(R.id.button_4); Button button5 = findViewById(R.id.button_5); Button button6 = findViewById(R.id.button_6); Button button7 = findViewById(R.id.button_7); Button button8 = findViewById(R.id.button_8); Button button9 = findViewById(R.id.button_9); Button button0 = findViewById(R.id.button_0); Button buttonClear = findViewById(R.id.button_clear); Button buttonPlus = findViewById(R.id.button_plus); Button buttonMinus = findViewById(R.id.button_minus); Button buttonMultiply = findViewById(R.id.button_multiply); Button buttonDivide = findViewById(R.id.button_divide); Button buttonEqual = findViewById(R.id.button_equal); button1.setOnClickListener(this); button2.setOnClickListener(this); button3.setOnClickListener(this); button4.setOnClickListener(this); button5.setOnClickListener(this); button6.setOnClickListener(this); button7.setOnClickListener(this); button8.setOnClickListener(this); button9.setOnClickListener(this); button0.setOnClickListener(this); buttonClear.setOnClickListener(this); buttonPlus.setOnClickListener(this); buttonMinus.setOnClickListener(this); buttonMultiply.setOnClickListener(this); buttonDivide.setOnClickListener(this); buttonEqual.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_0: handleNumberInput("0"); break; case R.id.button_1: handleNumberInput("1"); break; case R.id.button_2: handleNumberInput("2"); break; case R.id.button_3: handleNumberInput("3"); break; case R.id.button_4: handleNumberInput("4"); break; case R.id.button_5: handleNumberInput("5"); break; case R.id.button_6: handleNumberInput("6"); break; case R.id.button_7: handleNumberInput("7"); break; case R.id.button_8: handleNumberInput("8"); break; case R.id.button_9: handleNumberInput("9"); break; case R.id.button_plus: handleOperatorInput("+"); break; case R.id.button_minus: handleOperatorInput("-"); break; case R.id.button_multiply: handleOperatorInput("*"); break; case R.id.button_divide: handleOperatorInput("/"); break; case R.id.button_clear: handleClearInput(); break; case R.id.button_equal: handleEqualInput(); break; } } private void handleNumberInput(String number) { if (operator == null) { if (operand1 == null) { operand1 = number; } else { operand1 += number; } resultTextView.setText(operand1); } else { if (operand2 == null) { operand2 = number; } else { operand2 += number; } resultTextView.setText(operand2); } } private void handleOperatorInput(String op) { if (operand1 != null && operand2 != null) { handleEqualInput(); } operator = op; } private void handleClearInput() { operand1 = null; operand2 = null; operator = null; resultTextView.setText("0"); } private void handleEqualInput() { if (operand1 != null && operand2 != null && operator != null) { double result = 0; double op1 = Double.parseDouble(operand1); double op2 = Double.parseDouble(operand2); switch (operator) { case "+": result = op1 + op2; break; case "-": result = op1 - op2; break; case "*": result = op1 * op2; break; case "/": if (op2 != 0) { result = op1 / op2; } break; } operand1 = String.valueOf(result); operand2 = null; operator = null; resultTextView.setText(String.valueOf(result)); } } } ``` 这个计算器可以支持加减乘除四种运算,以及清空和计算结果。需要注意的是,这个计算器的计算方式是将运算符和两个数字分别存储在三个字符串变量中,当用户点击等号时才进行计算。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值