Xamarin Android - Criando uma Calculadora básica


Neste artigo vou mostrar como criar uma calculadora bem básica no Xamarin Android usando o Visual Studio 2015 e a linguagem C#.

Este é um artigo para inciantes que mostra de forma bem simples como criar uma calculadora para realizar as quatro operações básicas.

O artigo trabalha basicamente com controles Buttons e com eventos e não usa MVVM, o que seria mais indicado para o caso.

O projeto vai precisar as referências ao namespace System.Data.

Estou exibindo uma imagem no controle ImageView que foi colocada na pasta Resources/drawable com o nome de maco10.gif.

Recursos usados:

Nota: Baixe e use a versão Community 2015 do VS ela é grátis e é equivalente a versão Professional.

Criando o projeto no VS Community 2017

Abra o VS 2015 Community e clique em New Project;

Selecione a linguagem Visual C# e o template Android -> Blank App(Android)

Informe o nome Droid_Calculadora e clique no botão OK;

Abra o arquivo Main.axml na pasta Resources/layout e no modo Designer e a seguir inclua a partir da ToolBox os seguintes controles:

Abaixo vemos o leiaute no emulador do Xamarin e ao lado o respectivo código XML gerado :

        
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="#088da5"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imagemMac"
        android:layout_width="300dp"
        android:layout_height="80dp"
        android:src="@drawable/maco10"
        android:layout_gravity="center"
        android:scaleType="fitCenter" />
    <EditText
        android:inputType="text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/resultText"
        android:background="@android:color/darker_gray"
        android:textColor="@android:color/background_dark"
        android:textSize="@android:dimen/app_icon_size"
        android:cursorVisible="false"
        android:clickable="false"
        android:editable="false"
        android:enabled="false" />
    <EditText
        android:inputType="number"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/resultText2"
        android:background="@android:color/background_light"
        android:textColor="@android:color/background_dark"
        android:textSize="@android:dimen/app_icon_size"
        android:cursorVisible="false"
        android:enabled="false"
        android:editable="false"
        android:clickable="false" />
    <LinearLayout
        android:id="@+id/wrapper1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wrapper0"
        android:weightSum="1.0">
        <Button
            android:text="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".25"
            android:id="@+id/btn1" />
        <Button
            android:text="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn1"
            android:layout_alignTop="@+id/btn1"
            android:layout_weight=".25"
            android:id="@+id/btn2" />
        <Button
            android:text="3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn2"
            android:layout_alignTop="@+id/btn2"
            android:layout_weight=".25"
            android:id="@+id/btn3" />
        <Button
            android:text="DEL"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn3"
            android:layout_alignTop="@+id/btn3"
            android:layout_weight=".25"
            android:id="@+id/btnDel" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/wrapper2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wrapper1"
        android:weightSum="1.0">
        <Button
            android:text="4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/wrapper2"
            android:layout_weight=".25"
            android:id="@+id/btn4" />
        <Button
            android:text="5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn4"
            android:layout_alignTop="@+id/btn4"
            android:layout_weight=".25"
            android:id="@+id/btn5" />
        <Button
            android:text="6"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn5"
            android:layout_alignTop="@+id/btn5"
            android:layout_weight=".25"
            android:id="@+id/btn6" />
        <Button
            android:text="-"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn6"
            android:layout_alignTop="@+id/btn6"
            android:layout_weight=".25"
            android:id="@+id/btnSub" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/wrapper3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wrapper2"
        android:weightSum="1.0">
        <Button
            android:text="7"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/wrapper3"
            android:layout_weight=".25"
            android:id="@+id/btn7" />
        <Button
            android:text="8"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn7"
            android:layout_alignTop="@+id/btn7"
            android:layout_weight=".25"
            android:id="@+id/btn8" />
        <Button
            android:text="9"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn8"
            android:layout_alignTop="@+id/btn8"
            android:layout_weight=".25"
            android:id="@+id/btn9" />
        <Button
            android:text="x"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn9"
            android:layout_alignTop="@+id/btn9"
            android:layout_weight=".25"
            android:id="@+id/btnMul" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/wrapper4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wrapper3"
        android:weightSum="1.0">
        <Button
            android:text="."
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn7"
            android:layout_weight=".20"
            android:id="@+id/btnDot" />
        <Button
            android:text="0"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btnDot"
            android:layout_alignTop="@+id/btnDot"
            android:layout_weight=".20"
            android:id="@+id/btn0" />
        <Button
            android:text="="
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn0"
            android:layout_alignTop="@+id/btnDot"
            android:layout_weight=".20"
            android:id="@+id/btnEql" />
        <Button
            android:text="/"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btnEql"
            android:layout_alignTop="@+id/btnEql"
            android:layout_weight=".20"
            android:id="@+id/btnDiv" />
        <Button
            android:text="+"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btnDiv"
            android:layout_alignTop="@+id/btnDiv"
            android:layout_weight=".20"
            android:id="@+id/btnAdd" />
    </LinearLayout>
</LinearLayout>

Agora vamos definir o código no arquivo MainActivity.cs vinculado a nossa view Main.axml.

Tratando  a entrada do usuário e fazendo as quatro operações

Abra o arquivo MainActivity.cs e altere o código desse arquivo conforme abaixo:

using Android.App;
using Android.Widget;
using Android.OS;
using System;
using System.Data;
namespace Droid_Calculadora
{
    [Activity(Label = "Droid_Calculadora", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);
            ImageView img = FindViewById<ImageView>(Resource.Id.imagemMac);
            img.SetImageResource(Resource.Drawable.maco10);
            //Botões para entrada de valores
            Button num1 = (Button)FindViewById(Resource.Id.btn1);
            Button num2 = (Button)FindViewById(Resource.Id.btn2);
            Button num3 = (Button)FindViewById(Resource.Id.btn3);
            Button num4 = (Button)FindViewById(Resource.Id.btn4);
            Button num5 = (Button)FindViewById(Resource.Id.btn5);
            Button num6 = (Button)FindViewById(Resource.Id.btn6);
            Button num7 = (Button)FindViewById(Resource.Id.btn7);
            Button num8 = (Button)FindViewById(Resource.Id.btn8);
            Button num9 = (Button)FindViewById(Resource.Id.btn9);
            Button num0 = (Button)FindViewById(Resource.Id.btn0);
            //Botões para as operações matematicas
            Button equ = (Button)FindViewById(Resource.Id.btnEql);
            Button clr = (Button)FindViewById(Resource.Id.btnDel);
            Button dot = (Button)FindViewById(Resource.Id.btnDot);
            Button div = (Button)FindViewById(Resource.Id.btnDiv);
            Button mul = (Button)FindViewById(Resource.Id.btnMul);
            Button som = (Button)FindViewById(Resource.Id.btnAdd);
            Button sub = (Button)FindViewById(Resource.Id.btnSub);
            //texto para receber a entrada do usuário
            EditText resu = (EditText)FindViewById(Resource.Id.resultText);
            // Texto para exibir o resultado gerado
            EditText resu2 = (EditText)FindViewById(Resource.Id.resultText2);
            //sempre que o texto no EditText mudar a expressão será calculada
            resu.TextChanged += delegate
            {
                if (resu.Text == "")
                {
                    resu2.Text = "";
                }
                string x = resu.Text;
                try
                {
                    //Calcula a expressão
                    double result = Convert.ToDouble(new DataTable().Compute(x, null));
                    resu2.Text = result.ToString();
                }
                catch (Exception)
                {
                    //sem ação
                }
            };
            //define os eventos dos botões de comando
            num1.Click += delegate { resu.Text = resu.Text + num1.Text.ToString(); };
            num2.Click += delegate { resu.Text = resu.Text + num2.Text.ToString(); };
            num3.Click += delegate { resu.Text = resu.Text + num3.Text.ToString(); };
            num4.Click += delegate { resu.Text = resu.Text + num4.Text.ToString(); };
            num5.Click += delegate { resu.Text = resu.Text + num5.Text.ToString(); };
            num6.Click += delegate { resu.Text = resu.Text + num6.Text.ToString(); };
            num7.Click += delegate { resu.Text = resu.Text + num7.Text.ToString(); };
            num8.Click += delegate { resu.Text = resu.Text + num8.Text.ToString(); };
            num9.Click += delegate { resu.Text = resu.Text + num9.Text.ToString(); };
            num0.Click += delegate { resu.Text = resu.Text + num0.Text.ToString(); };
            //define os eventos das operações 
            dot.Click += delegate
            {
                string x = resu.Text;
                int l = x.Length;
                if (l != 0)
                {
                    string x2 = x.Substring(l - 1, 1);
                    if (x2 != ".")
                    {
                        if (x2 == "-" || x2 == "*" || x2 == "/" || x2 == "+")
                        {
                            string s1 = x.Substring(0, l - 1);
                            resu.Text = s1;
                        }
                        resu.Text = resu.Text + dot.Text.ToString();
                    }
                }
            };
            som.Click += delegate
            {
                string x = resu.Text;
                int l = x.Length;
                if (l != 0)
                {
                    string x2 = x.Substring(l - 1, 1);
                    if (x2 != "+")
                    {
                        if (x2 == "-" || x2 == "*" || x2 == "/" || x2 == ".")
                        {
                            string s1 = x.Substring(0, l - 1);
                            resu.Text = s1;
                        }
                        resu.Text = resu.Text + som.Text.ToString();
                    }
                }
            };
            sub.Click += delegate
            {
                string x = resu.Text;
                int l = x.Length;
                if (l != 0)
                {
                    string x2 = x.Substring(l - 1, 1);
                    if (x2 != "-")
                    {
                        if (x2 == "+" || x2 == "*" || x2 == "/" || x2 == ".")
                        {
                            string s1 = x.Substring(0, l - 1);
                            resu.Text = s1;
                        }
                        resu.Text = resu.Text + sub.Text.ToString();
                    }
                }
            };
            mul.Click += delegate
            {
                string x = resu.Text;
                int l = x.Length;
                if (l != 0)
                {
                    string x2 = x.Substring(l - 1, 1);
                    if (x2 != "*")
                    {
                        if (x2 == "-" || x2 == "+" || x2 == "/" || x2 == ".")
                        {
                            string s1 = x.Substring(0, l - 1);
                            resu.Text = s1;
                        }
                        resu.Text = resu.Text + "*";
                    }
                }
            };
            div.Click += delegate
            {
                string x = resu.Text;
                int l = x.Length;
                if (l != 0)
                {
                    string x2 = x.Substring(l - 1, 1);
                    if (x2 != "/")
                    {
                        if (x2 == "-" || x2 == "*" || x2 == "+" || x2 == ".")
                        {
                            string s1 = x.Substring(0, l - 1);
                            resu.Text = s1;
                        }
                        resu.Text = resu.Text + div.Text.ToString();
                    }
                }
            };
            clr.Click += delegate
            {
                string x = resu.Text;
                int l = x.Length;
                if (l != 0)
                {
                    string x2 = x.Substring(0, l - 1);
                    resu.Text = x2;
                    if (x2.Length != 0)
                    {
                        string x3 = x2.Substring(l - 2, 1);
                        if (x3 == "+" || x3 == "-" || x3 == "*" || x3 == "/" || x3 == ".")
                        {
                            try
                            {
                                double result = Convert.ToDouble(new DataTable().Compute(x.Substring(0, l - 2), null));
                                resu2.Text = result.ToString();
                            }
                            catch (Exception)
                            {
                               //sem ação
                            }
                        }
                    }
                }
            };
            equ.Click += delegate
            {
                if (resu2.Text != "")
                {
                    resu.Text = resu2.Text;
                    resu2.Text = "";
                }
            };
        }
        private void Resu_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            throw new System.NotImplementedException();
        }
    }
}

O código é bem simples e na verdade não esta levando em conta a precedência das operações o que pode gerar resultados inconsistentes. Fica como exercício implementar esse recurso.

Para as quatro operações básicas o código funciona.

Executando o projeto usando o emulador Genymotion iremos obter o seguinte resultado:

Pegue o projeto aqui :   Droid_Calculadora.zip (sem as referências)

Se dissermos que temos comunhão com ele (Jesus), e andarmos em trevas, mentimos, e não praticamos a verdade.
Mas, se andarmos na luz, como ele na luz está, temos comunhão uns com os outros, e o sangue de Jesus Cristo, seu Filho, nos purifica de todo o pecado.

1 João 1:6,7

Veja os Destaques e novidades do SUPER DVD Visual Basic (sempre atualizado) : clique e confira !

Quer migrar para o VB .NET ?

Quer aprender C# ??

Quer aprender os conceitos da Programação Orientada a objetos ?

Quer aprender o gerar relatórios com o ReportViewer no VS 2013 ?

Referências:


José Carlos Macoratti