MainActivity.cs
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
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]}";
}
}
|


0 comments:
Post a Comment
Note: only a member of this blog may post a comment.