Android——在线计算器完整代码

 实现效果

 

一、xml布局文件

这里采用线性布局,关于计算器的布局,可以查看之前的文章。

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

    <TextView
        android:id="@+id/textResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:gravity="right"
        android:text="" />

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

        <Button
            android:id="@+id/btnCLs"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="C"/>
        <Button
            android:id="@+id/btnDel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="Del"/>


    </LinearLayout>

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

        <Button
            android:id="@+id/btnOne"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1"/>
        <Button
            android:id="@+id/btnTwo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="2"/>
        <Button
            android:id="@+id/btnThree"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3"/>
        <Button
            android:id="@+id/btnAdd"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="+"/>

    </LinearLayout>

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

        <Button
            android:id="@+id/btnFour"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="4"/>
        <Button
            android:id="@+id/btnFive"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="5"/>
        <Button
            android:id="@+id/btnSix"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="6"/>
        <Button
            android:id="@+id/btnReduce"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="-"/>

    </LinearLayout>

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

        <Button
            android:id="@+id/btnSeven"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="7"/>
        <Button
            android:id="@+id/btnEight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="8"/>
        <Button
            android:id="@+id/btnNine"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="9"/>
        <Button
            android:id="@+id/btnMul"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="*"/>

    </LinearLayout>

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

        <Button
            android:id="@+id/btnZero"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="0"/>
        <Button
            android:id="@+id/btnPoint"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="."/>
        <Button
            android:id="@+id/btnEquals"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="="/>
        <Button
            android:id="@+id/btnChu"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="÷"/>

    </LinearLayout>
</LinearLayout>

二、MainActivity.java文件 

1.创建每个按钮的对象

2.实例化每个按钮 通过每个按钮的id进行实例化创建

3.设置每个按钮的点击事件即监听按钮
switch通过id判断被点击的按钮属于哪个控件。如果是数字或小数点,setText(str + ((Button) view).getText())。
如果是加减乘除,setText(str + " " + ((Button) view).getText() + " ")。这里的空格是很巧妙的,对下面运算结果中提取两个数字大有帮助。
如果是清空按钮,setText("")。
如果是删了后面一位数字,setText(str.substring(0,str.length()-1))。调用substring(beginIndex,endIndex)函数。substring函数是用来截取一个字段的一部分。
如果是等于按钮,调用getresult()方法。

4.创建运算结果的方法getresult()。
首先将其中的两个数字和运算符分割出来,调用substring(0,exp.indexOf(" "))函数。indexOf函数用于返回[目标字符串]在[源字符串]中的位置。
接着判断两个数都有,还是第一个数/第二个数为空,分情况写代码。

5.MainActivity.java代码如下:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{//实现鼠标点击的事件的监听接口

    //创建每个按钮的对象
    //数字按钮
    Button btnOne,btnTwo,btnThree,btnFour,btnFive,btnSix,btnSeven,btnEight,btnNine,btnZero;
    //加减乘除
    Button btnChu,btnAdd,btnReduce,btnMul;
    //其他按钮
    Button btnCLs,btnDel,btnEquals,btnPoint;
    //文本框
    TextView textResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//设置采用哪一个布局文件

        //实例化每个按钮 通过每个按钮的id进行实例化创建
        btnOne = (Button) findViewById(R.id.btnOne);
        btnTwo = (Button) findViewById(R.id.btnTwo);
        btnThree = (Button) findViewById(R.id.btnThree);
        btnFour = (Button) findViewById(R.id.btnFour);
        btnFive = (Button) findViewById(R.id.btnFive);
        btnSix = (Button) findViewById(R.id.btnSix);
        btnSeven = (Button) findViewById(R.id.btnSeven);
        btnEight = (Button) findViewById(R.id.btnEight);
        btnNine = (Button) findViewById(R.id.btnNine);
        btnZero = (Button) findViewById(R.id.btnZero);

        btnChu = (Button) findViewById(R.id.btnChu);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnReduce = (Button) findViewById(R.id.btnReduce);
        btnMul = (Button) findViewById(R.id.btnMul);

        btnCLs = (Button) findViewById(R.id.btnCLs);
        btnDel = (Button) findViewById(R.id.btnDel);
        btnEquals = (Button) findViewById(R.id.btnEquals);
        btnPoint = (Button) findViewById(R.id.btnPoint);

        textResult = (TextView)findViewById(R.id.textResult);

        //设置每个按钮的点击事件即监听按钮
        btnOne.setOnClickListener(this);
        btnTwo.setOnClickListener(this);
        btnThree.setOnClickListener(this);
        btnFour.setOnClickListener(this);
        btnFive.setOnClickListener(this);
        btnSix.setOnClickListener(this);
        btnSeven.setOnClickListener(this);
        btnEight.setOnClickListener(this);
        btnNine.setOnClickListener(this);
        btnZero.setOnClickListener(this);

        btnChu.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        btnReduce.setOnClickListener(this);
        btnMul.setOnClickListener(this);

        btnCLs.setOnClickListener(this);
        btnDel.setOnClickListener(this);
        btnEquals.setOnClickListener(this);
        btnPoint.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        String str = textResult.getText().toString(); //获取当前textview文本

        switch (view.getId()) {
            case R.id.btnOne:
            case R.id.btnTwo:
            case R.id.btnThree:
            case R.id.btnFour:
            case R.id.btnFive:
            case R.id.btnSix:
            case R.id.btnSeven:
            case R.id.btnEight:
            case R.id.btnNine:
            case R.id.btnZero:
            case R.id.btnPoint:
                textResult.setText(str + ((Button) view).getText());
                break;

            case R.id.btnChu:
            case R.id.btnAdd:
            case R.id.btnReduce:
            case R.id.btnMul:
                textResult.setText(str + " " + ((Button) view).getText() + " ");
                break;

            case R.id.btnCLs:
                textResult.setText("");
                break;

            case R.id.btnDel:
                if(str != null && !str.equals("")){
                    textResult.setText(str.substring(0,str.length()-1));   // substring(beginIndex, endIndex)  [beginIndex, endIndex)
                }                                                          //  str="123456"   str.substring(0,3) ="123";         "1237 + 10"
                break;

            case R.id.btnEquals:
                getresult();
        }
    }

    private void getresult() {
        String exp = textResult.getText().toString(); //从textview获取整个文本
        if(exp == null || exp.equals("")){
            return;
        }
        if(!exp.contains(" ")){
            return;
        }

        //将其中的两个数字和运算符分割出来
        float result = 0;                                                   // exp ="123 + 5"
        String num1 = exp.substring(0,exp.indexOf(" "));                      // num1 ="123"
        String ex = exp.substring(exp.indexOf(" ") + 1,exp.indexOf(" ") + 2); // ex="+"
        String num2 = exp.substring(exp.indexOf(" ") + 3);                    // num2="5"

        //如果两个数字都不为空则判断运算符进行运算
        if(!num1.equals("") && !num2.equals("")) {
            float d1 = Float.parseFloat(num1);
            float d2 = Float.parseFloat(num2);

            if (ex.equals("+")) {
                result = d1 + d2;
            } else if (ex.equals("-")) {
                result = d1 - d2;
            } else if (ex.equals("*")) {
                result = d1 * d2;
            } else if (ex.equals("÷")) {
                if (d2 == 0) {
                    result = 0;
                } else {
                    result = d1 / d2;
                }
            }
            textResult.setText(result + "");
        }else if(!num1.equals("") && num2.equals("")){
            textResult.setText(exp.substring(0,exp.indexOf(" ")));   //textResult.setText(exp);
        }else if(num1.equals("") && !num2.equals("")){
            float d3 = Float.parseFloat(num2);
            if(ex.equals("+")){
                result = 0 + d3;
            }else if(ex.equals("-")){
                result = 0 - d3;
            }else if(ex.equals("*")){
                result = 0 * d3;
            }else if(ex.equals("÷")){
                result = 0;
            }
            textResult.setText(result + "");
        }else{
            textResult.setText("");
        }
    }
}

四、总结

总体来说很不错,也实现了清除后面一个数的功能,但还未能实现负数的运算 。

  • 19
    点赞
  • 104
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio是一个强大的集成开发环境,可用于开发Android应用程序。以下是一个简单的计算器应用程序的源代码示例: ```java package com.example.calculator; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText display; String input = ""; String operator = ""; double num1, num2, result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); display = findViewById(R.id.display); } public void onNumberClick(View view) { Button button = (Button) view; input += button.getText().toString(); display.setText(input); } public void onOperatorClick(View view) { Button button = (Button) view; operator = button.getText().toString(); num1 = Double.parseDouble(input); input = ""; } public void onCalculateClick(View view) { num2 = Double.parseDouble(input); switch (operator) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": result = num1 / num2; break; } display.setText(String.valueOf(result)); } } ``` 这段代码演示了一个简单的计算器应用程序的功能。用户可以通过点击按钮输入数字和运算符,然后计算器会根据用户输入的操作进行计算,并在显示框中显示结果。这个示例代码使用了Android Studio提供的组件和方法来实现计算器功能。这个简单的计算器应用程序可以作为学习Android开发的起点,让开发者熟悉Android Studio的使用和基本的应用程序开发流程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值