XML:
<?xml version="1.0" encoding="utf-8"? android:columnCount="4"
> android:rowCount="5"
<LinearLayout android:layout_marginTop="12dp">
xmlns:android="[Link]
com/apk/res/android" <Button android:text="7"/>
android:layout_width="match_parent" <Button android:text="8"/>
<Button android:text="9"/>
android:layout_height="match_parent" <Button android:text="/"/>
android:orientation="vertical"
android:padding="16dp" <Button android:text="4"/>
android:layout_marginTop="150dp" <Button android:text="5"/>
android:background="#F2F2F2"> <Button android:text="6"/>
<Button android:text="*"/>
<TextView
android:id="@+id/txtDisplay" <Button android:text="1"/>
<Button android:text="2"/>
android:layout_width="match_parent" <Button android:text="3"/>
android:layout_height="80dp" <Button android:text="-"/>
android:background="#FFFFFF"
android:text="0" <Button android:text="0"/>
android:textSize="32sp" <Button android:text="."/>
android:gravity="end| <Button android:text="="/>
center_vertical" <Button android:text="+"/>
android:padding="12dp"
android:textStyle="bold"/> <Button
android:text="C"
<GridLayout
android:id="@+id/gridCalculator" android:layout_columnSpan="4"/>
</GridLayout>
android:layout_width="match_parent"
</LinearLayout>
android:layout_height="wrap_content"
Java:
package [Link]; [Link]
vity;
import [Link];
import [Link]; public class MainActivity extends
import [Link]; AppCompatActivity {
import [Link];
import [Link]; TextView txtDisplay;
import [Link]; GridLayout gridCalculator;
import String input = "";
double firstValue = 0; operator = value;
String operator = ""; input = "";
}
@Override break;
protected void onCreate(Bundle
savedInstanceState) { case "=":
if (![Link]() && !
[Link](savedInstanceState); [Link]()) {
double secondValue =
setContentView([Link].activity_main); [Link](input);
double result = 0;
txtDisplay =
findViewById([Link]); try {
gridCalculator = switch (operator) {
findViewById([Link]); case "+": result =
firstValue + secondValue; break;
// Attach listener to all buttons case "-": result =
inside GridLayout firstValue - secondValue; break;
for (int i = 0; i < case "*": result =
[Link](); i++) { firstValue * secondValue; break;
View v = case "/":
[Link](i); if (secondValue ==
if (v instanceof Button) { 0) {
((Button)
v).setOnClickListener(this::onButtonClick [Link](this,
); "Cannot
} divide by zero",
}
} Toast.LENGTH_SHORT).show();
return;
private void onButtonClick(View view) }
{ result = firstValue /
String value = ((Button) secondValue;
view).getText().toString(); break;
}
switch (value) {
case "C": [Link]([Link](result));
input = ""; input =
operator = ""; [Link](result);
firstValue = 0; operator = "";
[Link]("0"); } catch (Exception e) {
break;
[Link]("Error");
case "+": input = "";
case "-": }
case "*": }
case "/": break;
if (![Link]()) {
firstValue = default: // Numbers & decimal
[Link](input); input += value;
[Link](input); }
} }