Android Simple Calculator (Java & XML)
1. XML Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<EditText
android:id="@+id/edtNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/edtNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal" />
<TextView
android:id="@+id/txtResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="20sp"
android:padding="10dp"/>
<Button android:id="@+id/btnAdd" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Add" />
<Button android:id="@+id/btnSubtract" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Subtract" />
<Button android:id="@+id/btnMultiply" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Multiply" />
<Button android:id="@+id/btnDivide" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Divide" />
</LinearLayout>
2. Java Code ([Link])
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
EditText edtNumber1, edtNumber2;
TextView txtResult;
Button btnAdd, btnSubtract, btnMultiply, btnDivide;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
edtNumber1 = findViewById([Link].edtNumber1);
edtNumber2 = findViewById([Link].edtNumber2);
txtResult = findViewById([Link]);
btnAdd = findViewById([Link]);
btnSubtract = findViewById([Link]);
btnMultiply = findViewById([Link]);
btnDivide = findViewById([Link]);
[Link](v -> calculate('+'));
[Link](v -> calculate('-'));
[Link](v -> calculate('*'));
[Link](v -> calculate('/'));
}
private void calculate(char operation) {
String num1 = [Link]().toString();
String num2 = [Link]().toString();
if ([Link]() || [Link]()) {
[Link](this, "Please enter both numbers", Toast.LENGTH_SHORT).show();
return;
}
double number1 = [Link](num1);
double number2 = [Link](num2);
double result = 0;
switch (operation) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case '*': result = number1 * number2; break;
case '/':
if (number2 == 0) {
[Link](this, "Cannot divide by zero", Toast.LENGTH_SHORT).show();
return;
}
result = number1 / number2;
break;
}
[Link]("Result: " + result);
}
}