9b798867fde00a1f1b477cfc600f3be2bd0e696e
[nit.git] / examples / calculator / src / calculator_android.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Android calculator application
18 module calculator_android is
19 app_name "app.nit Calc."
20 app_version(0, 1, git_revision)
21 java_package "org.nitlanguage.calculator"
22
23 # Lock in portrait mode
24 android_manifest_activity """android:screenOrientation="portrait""""
25 end
26
27 # FIXME the next line should import `android` only when it uses nit_activity
28 import android::log
29 import android::ui
30
31 import calculator_logic
32
33 redef class Activity
34 super EventCatcher
35
36 private var context = new CalculatorContext
37
38 # The main display, at the top of the screen
39 private var display: EditText
40
41 # Maps operators as `String` to their `Button`
42 private var op2but = new HashMap[String, Button]
43
44 # Has this window been initialized?
45 private var inited = false
46
47 redef fun on_start
48 do
49 super
50
51 if inited then return
52 inited = true
53
54 # Setup UI
55 var layout = new NativeLinearLayout(native)
56 layout.set_vertical
57
58 # Display screen
59 var display = new EditText
60 layout.add_view_with_weight(display.native, 1.0)
61 display.text_size = 36.0
62 self.display = display
63
64 # Buttons; numbers and operators
65 var ops = [["7", "8", "9", "+"],
66 ["4", "5", "6", "-"],
67 ["1", "2", "3", "*"],
68 ["0", ".", "C", "/"],
69 ["="]]
70
71 for line in ops do
72 var buts_layout = new NativeLinearLayout(native)
73 buts_layout.set_horizontal
74 layout.add_view_with_weight(buts_layout, 1.0)
75
76 for op in line do
77 var but = new Button
78 but.event_catcher = self
79 but.text = op
80 but.text_size = 40
81 buts_layout.add_view_with_weight(but.native, 1.0)
82 op2but[op] = but
83 end
84 end
85
86 native.content_view = layout
87 end
88
89 redef fun catch_event(event)
90 do
91 if event isa ClickEvent then
92 var sender = event.sender
93 var op = sender.text
94
95 if op == "." then
96 sender.enabled = false
97 context.switch_to_decimals
98 else if op.is_numeric then
99 var n = op.to_i
100 context.push_digit n
101 else
102 op2but["."].enabled = true
103 context.push_op op.chars.first
104 end
105
106 display.text = context.display_text
107 end
108 end
109 end