Android实现简易计算功能

本文实例为大家分享了Android实现简易计算功能的具体代码,供大家参考,具体内容如下
效果如图:
Android实现简易计算功能
文章图片

activity_main.xml


arrays.xml
请选择运算符+-*/

MainActivity
package com.jld.homework; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity {String op; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Spinner spinner = (Spinner) this.findViewById(R.id.operator); //获取活动布局中的Spinner对象//为Spinner注册内部监听器对象spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView parent, View view, int position, long id) {//将Spinner选项的值赋值给成员变量op(保存算术运算符)op = ((TextView) view).getText().toString(); }@Overridepublic void onNothingSelected(AdapterView parent) {}}); //各类组件Button calcButton = findViewById(R.id.calc); EditText firstNum = findViewById(R.id.firstNum); EditText secondNum = findViewById(R.id.secondNum); TextView result = findViewById(R.id.result); //计算核心calcButton.setOnClickListener(v -> {switch (op) {case "+": {double r = Double.parseDouble(firstNum.getText().toString()) + Double.parseDouble(secondNum.getText().toString()); result.setText(String.valueOf(r)); break; }case "-": {double r = Double.parseDouble(firstNum.getText().toString()) - Double.parseDouble(secondNum.getText().toString()); result.setText(String.valueOf(r)); break; }case "*": {double r = Double.parseDouble(firstNum.getText().toString()) * Double.parseDouble(secondNum.getText().toString()); result.setText(String.valueOf(r)); break; }case "/": {double r = Double.parseDouble(firstNum.getText().toString()) / Double.parseDouble(secondNum.getText().toString()); result.setText(String.valueOf(r)); break; }default://非法情况报错result.setText(R.string.ERROR); break; }}); }}

【Android实现简易计算功能】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读