-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainActivity.java
More file actions
85 lines (73 loc) · 2.96 KB
/
Copy pathMainActivity.java
File metadata and controls
85 lines (73 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.example.calculator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button buttonAdd, buttonSub, buttonMul, buttonDiv;
EditText editTextN1, editTextN2;
TextView textView;
int num1, num2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
// UI references
buttonAdd = findViewById(R.id.btn_add);
buttonSub = findViewById(R.id.btn_sub);
buttonMul = findViewById(R.id.btn_mul);
buttonDiv = findViewById(R.id.btn_div);
editTextN1 = findViewById(R.id.number1);
editTextN2 = findViewById(R.id.number2);
textView = findViewById(R.id.answer);
// Set click listeners
buttonAdd.setOnClickListener(this);
buttonSub.setOnClickListener(this);
buttonMul.setOnClickListener(this);
buttonDiv.setOnClickListener(this);
// Handle window insets
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
@Override
public void onClick(View v) {
String input1 = editTextN1.getText().toString().trim();
String input2 = editTextN2.getText().toString().trim();
if (input1.isEmpty() || input2.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show();
return;
}
try {
num1 = Integer.parseInt(input1);
num2 = Integer.parseInt(input2);
} catch (NumberFormatException e) {
Toast.makeText(this, "Invalid number entered", Toast.LENGTH_SHORT).show();
return;
}
if (v.getId() == R.id.btn_add) {
textView.setText("Answer is: " + (num1 + num2));
} else if (v.getId() == R.id.btn_sub) {
textView.setText("Answer is: " + (num1 - num2));
} else if (v.getId() == R.id.btn_mul) {
textView.setText("Answer is: " + (num1 * num2));
} else if (v.getId() == R.id.btn_div) {
if (num2 != 0) {
textView.setText("Answer is: " + (num1 / num2));
} else {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show();
textView.setText("Error");
}
}
}
}