Make a CALCULATOR App with Xamarin Android #2 (Code)

8  comments

Learn how to code the logic of this simple calculator in C#. It’s easier than you think and it is certainly a lot of fun!

 

This post contains all the code that’s been written in this YouTube video.

 

 

You can also check out the GitHub repository: https://github.com/ResoCoder/Simple-Calculator—Xamarin-Android

MainActivity.cs

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Views;
using System;

namespace CalculatorAndroidTut
{
    [Activity(Label = "CalculatorAndroidTut", MainLauncher = true)]
    public class MainActivity : Activity
    {
        private TextView calculatorText;

        private string[] numbers = new string[2];
        private string @operator;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            calculatorText = FindViewById<TextView>(Resource.Id.calculator_text_view);
        }

        [Java.Interop.Export("ButtonClick")]
        public void ButtonClick (View v)
        {
            Button button = (Button)v;
            if ("0123456789.".Contains(button.Text))
                AddDigitOrDecimalPoint(button.Text);
            else if ("÷×+-".Contains(button.Text))
                AddOperator(button.Text);
            else if ("=" == button.Text)
                Calculate();
            else
                Erase();
        }

        private void AddDigitOrDecimalPoint(string value)
        {
            int index = @operator == null ? 0 : 1;

            if (value == "." && numbers[index].Contains("."))
                return;

            numbers[index] += value;

            UpdateCalculatorText();
        }

        private void AddOperator(string value)
        {
            if (numbers[1] != null)
            {
                Calculate(value);
                return;
            }

            @operator = value;

            UpdateCalculatorText();
        }

        private void Calculate(string newOperator = null)
        {
            double? result = null;
            double? first = numbers[0] == null ? null : (double?)double.Parse(numbers[0]);
            double? second = numbers[1] == null ? null : (double?)double.Parse(numbers[1]);

            switch (@operator)
            {
                case "÷":
                    result = first / second;
                    break;
                case "×":
                    result = first * second;
                    break;
                case "+":
                    result = first + second;
                    break;
                case "-":
                    result = first - second;
                    break;
            }

            if (result != null)
            {
                numbers[0] = result.ToString();
                @operator = newOperator;
                numbers[1] = null;
                UpdateCalculatorText();
            }
        }

        private void Erase()
        {
            numbers[0] = numbers[1] = null;
            @operator = null;
            UpdateCalculatorText();
        }

        private void UpdateCalculatorText() => calculatorText.Text = $"{numbers[0]} {@operator} {numbers[1]}";
    }
}

 

About the author 

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a freelancer and most importantly developer educator, he is set on helping other people succeed in their Flutter app development career.

You may also like

    • If you calculate by not pressing the “=” button but you rather press an operator like “+” it will calculate. Then it will put the operator (in this case “+”) after the result of the calculation so you can continue calculating with that result.

  • I am getting this exception when try to start calculate:
    “Java.Lang.IllegalStateException: Could not find a method ButtonClick(View) in the activity class “

  • @rakesh Lilhare
    trust me , his channel has LOTS of useful tuto, I’ve search for many guides (but apparently results from India floods my results). When I found Reso coder no more Hin-glish, thx resocoder!

  • thanks! Great tutorial. Can you help me? If click “.” without any digit app will close, and any debuging don’t help. I try make “If” to add numbers[index] = “0.” then value == “.” && numbers[index] == null in private void AddDigitOrDecimalPoint(string value) . But app close early :(

  • it is not working everytime I press the buttons the app is crashing and there is an error message that tells something about the android:onClick

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >