关于androidstudio简易计算器可以给个代码例子吗
时间: 2024-05-06 17:21:10 浏览: 87
andriod studio 简单计算器示例
3星 · 编辑精心推荐
当然可以,以下是一个简单的安卓计算器的代码(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 etNum1, etNum2, etResult;
Button btnAdd, btnSubtract, btnMultiply, btnDivide;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNum1 = findViewById(R.id.etNum1);
etNum2 = findViewById(R.id.etNum2);
etResult = findViewById(R.id.etResult);
btnAdd = findViewById(R.id.btnAdd);
btnSubtract = findViewById(R.id.btnSubtract);
btnMultiply = findViewById(R.id.btnMultiply);
btnDivide = findViewById(R.id.btnDivide);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(etNum1.getText().toString());
double num2 = Double.parseDouble(etNum2.getText().toString());
double result = num1 + num2;
etResult.setText(String.valueOf(result));
}
});
btnSubtract.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(etNum1.getText().toString());
double num2 = Double.parseDouble(etNum2.getText().toString());
double result = num1 - num2;
etResult.setText(String.valueOf(result));
}
});
btnMultiply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(etNum1.getText().toString());
double num2 = Double.parseDouble(etNum2.getText().toString());
double result = num1 * num2;
etResult.setText(String.valueOf(result));
}
});
btnDivide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(etNum1.getText().toString());
double num2 = Double.parseDouble(etNum2.getText().toString());
double result = num1 / num2;
etResult.setText(String.valueOf(result));
}
});
}
}
```
注意:以上代码只是一个简单的计算器,缺少输入验证和错误处理等功能,仅供参考。
阅读全文