5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | 16dp
20 | 8dp
21 |
22 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2017 Andrius Baruckis
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | #
16 |
17 | #Sat Sep 02 08:22:16 EEST 2017
18 | distributionBase=GRADLE_USER_HOME
19 | distributionPath=wrapper/dists
20 | zipStoreBase=GRADLE_USER_HOME
21 | zipStorePath=wrapper/dists
22 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
23 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_delete_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
22 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/test/java/com/baruckis/calculator/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Andrius Baruckis
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.baruckis.calculator
18 |
19 | import org.junit.Test
20 |
21 | import org.junit.Assert.*
22 |
23 | /**
24 | * Example local unit test, which will execute on the development machine (host).
25 | *
26 | * See [testing documentation](http://d.android.com/tools/testing).
27 | */
28 | class ExampleUnitTest {
29 | @Test
30 | fun addition_isCorrect() {
31 | assertEquals(4, 2 + 2)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android Calculator
2 |
3 | Prototype Android app of Windows 10 style calculator with memory and history actions written in Kotlin.
4 |
5 | This app was created for my personal blog post ["Let’s learn Kotlin by building Android calculator app"](http://www.baruckis.com/android/lets-learn-kotlin-by-building-android-calculator-app).
6 | It is created for self learning purpose to explore Kotlin language features.
7 |
8 | ### App screen recording:
9 |
10 | 
11 |
12 | ## License
13 |
14 | Copyright 2017 Andrius Baruckis.
15 |
16 | Licensed under the Apache License, Version 2.0 (the "License");
17 | you may not use this file except in compliance with the License.
18 | You may obtain a copy of the License at
19 |
20 | http://www.apache.org/licenses/LICENSE-2.0
21 |
22 | Unless required by applicable law or agreed to in writing, software
23 | distributed under the License is distributed on an "AS IS" BASIS,
24 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 | See the License for the specific language governing permissions and
26 | limitations under the License.
27 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/main_menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_history_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
22 |
25 |
26 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2017 Andrius Baruckis
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | #
16 |
17 | # Project-wide Gradle settings.
18 |
19 | # IDE (e.g. Android Studio) users:
20 | # Gradle settings configured through the IDE *will override*
21 | # any settings specified in this file.
22 |
23 | # For more details on how to configure your build environment visit
24 | # http://www.gradle.org/docs/current/userguide/build_environment.html
25 |
26 | # Specifies the JVM arguments used for the daemon process.
27 | # The setting is particularly useful for tweaking memory settings.
28 | org.gradle.jvmargs=-Xmx1536m
29 |
30 | # When configured, Gradle will run in incubating parallel mode.
31 | # This option should only be used with decoupled projects. More details, visit
32 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
33 | # org.gradle.parallel=true
34 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/baruckis/calculator/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Andrius Baruckis
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.baruckis.calculator
18 |
19 | import android.support.test.InstrumentationRegistry
20 | import android.support.test.runner.AndroidJUnit4
21 |
22 | import org.junit.Test
23 | import org.junit.runner.RunWith
24 |
25 | import org.junit.Assert.*
26 |
27 | /**
28 | * Instrumented test, which will execute on an Android device.
29 | *
30 | * See [testing documentation](http://d.android.com/tools/testing).
31 | */
32 | @RunWith(AndroidJUnit4::class)
33 | class ExampleInstrumentedTest {
34 | @Test
35 | fun useAppContext() {
36 | // Context of the app under test.
37 | val appContext = InstrumentationRegistry.getTargetContext()
38 | assertEquals("com.baruckis.calculator", appContext.packageName)
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
28 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | @color/colorBlueGrey
20 | @android:color/black
21 | @color/colorTeal
22 |
23 | @android:color/white
24 | @android:color/black
25 | @android:color/darker_gray
26 | @color/colorTeal
27 | @android:color/black
28 | @color/colorBlueGrey
29 | @color/colorLightGrey
30 | @android:color/white
31 |
32 | #009688
33 | #E0E0E0
34 | #607D8B
35 |
36 |
37 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
26 |
27 |
31 |
32 |
35 |
36 |
40 |
41 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_history_action_list_dialog_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
29 |
30 |
37 |
38 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Andrius Baruckis
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | apply plugin: 'com.android.application'
18 |
19 | apply plugin: 'kotlin-android'
20 |
21 | apply plugin: 'kotlin-android-extensions'
22 |
23 | android {
24 | compileSdkVersion 26
25 | buildToolsVersion "26.0.2"
26 | defaultConfig {
27 | applicationId "com.baruckis.calculator"
28 | minSdkVersion 21
29 | targetSdkVersion 26
30 | versionCode 1
31 | versionName "1.0"
32 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
33 | }
34 | buildTypes {
35 | release {
36 | minifyEnabled false
37 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
38 | }
39 | }
40 | }
41 |
42 | dependencies {
43 | implementation fileTree(dir: 'libs', include: ['*.jar'])
44 | implementation 'com.android.support:support-v4:26.1.0'
45 | implementation 'com.android.support:design:26.1.0'
46 | implementation 'com.android.support:recyclerview-v7:26.1.0'
47 | androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.0', {
48 | exclude group: 'com.android.support', module: 'support-annotations'
49 | })
50 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
51 | implementation 'com.android.support:appcompat-v7:26.1.0'
52 | testImplementation 'junit:junit:4.12'
53 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
54 |
55 | compile 'com.android.support:design:26.1.0'
56 | }
57 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | Calculator
19 |
20 | MC
21 | MR
22 | M+
23 | M-
24 | MS
25 |
26 | %
27 | √
28 | x²
29 | ⅟x
30 | CE
31 | C
32 | ⌫
33 | ÷
34 | ±
35 | ,
36 | =
37 | +
38 | −
39 | ×
40 |
41 | 9
42 | 8
43 | 7
44 | 6
45 | 5
46 | 4
47 | 3
48 | 2
49 | 1
50 | 0
51 |
52 | History
53 |
54 | History:
55 | Clear history
56 | "History result: "
57 | "There's no history yet."
58 | History cleared
59 |
60 | Memory cleared
61 | Memory recalled
62 | "Memory added: "
63 | "Memory subtracted: "
64 | "Memory stored: "
65 |
66 |
67 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_history_action_list_dialog.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
24 |
32 |
33 |
42 |
43 |
50 |
51 |
52 |
53 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
28 |
33 |
38 |
43 |
48 |
53 |
58 |
63 |
68 |
73 |
78 |
83 |
88 |
93 |
98 |
103 |
108 |
113 |
118 |
123 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/baruckis/calculator/HistoryActionListDialogFragment.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Andrius Baruckis
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.baruckis.calculator
18 |
19 | import android.content.Context
20 | import android.os.Bundle
21 | import android.support.design.widget.BottomSheetDialogFragment
22 | import android.support.v7.widget.LinearLayoutManager
23 | import android.support.v7.widget.RecyclerView
24 | import android.view.LayoutInflater
25 | import android.view.View
26 | import android.view.ViewGroup
27 | import android.widget.ImageButton
28 | import android.widget.LinearLayout
29 | import android.widget.TextView
30 | import android.widget.Toast
31 | import java.util.*
32 |
33 |
34 | /**
35 | *
36 | * A fragment that shows a list of items as a modal bottom sheet.
37 | *
38 | * You activity (or fragment) needs to implement [HistoryActionListDialogFragment.Listener].
39 | */
40 | class HistoryActionListDialogFragment : BottomSheetDialogFragment() {
41 |
42 | // If ? is inserted after any type name, we have explicitly instructed the compiler that the value of the type can either store an object reference or can be null.
43 | private var mListener: Listener? = null
44 |
45 | private lateinit var mData: ArrayList
46 |
47 | override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
48 | savedInstanceState: Bundle?): View? {
49 | return inflater!!.inflate(R.layout.fragment_history_action_list_dialog, container, false)
50 | }
51 |
52 | override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
53 | // Initializing an ArrayList in one line when fragment is already attached to Activity and string resources are available to reach.
54 | mData = ArrayList(Arrays.asList(getString(R.string.no_history)))
55 |
56 | val data = arguments.getStringArrayList(ARG_HISTORY_ACTION)
57 | if (data.isNotEmpty()) {
58 | mData.clear()
59 | mData.addAll(data)
60 | }
61 |
62 | val recyclerView = view!!.findViewById(R.id.list) as RecyclerView?
63 | recyclerView!!.layoutManager = LinearLayoutManager(context)
64 | recyclerView.adapter = ItemAdapter(mData)
65 |
66 | val buttonClearHistory: ImageButton = view.findViewById(R.id.button_clear_history)
67 | buttonClearHistory.setOnClickListener {
68 | data.clear()
69 | mData.clear()
70 | mData.add(getString(R.string.no_history))
71 | recyclerView.adapter.notifyDataSetChanged()
72 | Toast.makeText(activity, getString(R.string.history_cleared), Toast.LENGTH_SHORT).show()
73 | }
74 | }
75 |
76 | override fun onAttach(context: Context?) {
77 | super.onAttach(context)
78 | val parent = parentFragment
79 | if (parent != null) {
80 | mListener = parent as Listener
81 | } else {
82 | mListener = context as Listener?
83 | }
84 | }
85 |
86 | override fun onDetach() {
87 | mListener = null
88 | super.onDetach()
89 | }
90 |
91 | interface Listener {
92 | fun onHistoryItemClicked(resultText: String)
93 | }
94 |
95 | private inner class ViewHolder internal constructor(inflater: LayoutInflater, parent: ViewGroup) : RecyclerView.ViewHolder(inflater.inflate(R.layout.fragment_history_action_list_dialog_item, parent, false)) {
96 |
97 | internal val rowLayout: LinearLayout = itemView.findViewById(R.id.row) as LinearLayout
98 | internal val actionTextView: TextView = itemView.findViewById(R.id.action) as TextView
99 | internal val resultTextView: TextView = itemView.findViewById(R.id.result) as TextView
100 |
101 | init {
102 | rowLayout.setOnClickListener {
103 | if (mListener != null) {
104 | // Operator with !! allows to bypass nullability checking by the Kotlin compiler.
105 | mListener!!.onHistoryItemClicked(resultTextView.text.toString())
106 | dismiss()
107 | }
108 | }
109 | }
110 |
111 | }
112 |
113 | private inner class ItemAdapter internal constructor(private val mHistoryActionList: ArrayList) : RecyclerView.Adapter() {
114 |
115 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
116 | return ViewHolder(LayoutInflater.from(parent.context), parent)
117 | }
118 |
119 | override fun onBindViewHolder(holder: ViewHolder, position: Int) {
120 | // Regular expression lookbehind with delimiter "="
121 | val reg = Regex("(?<=[=])")
122 | val historyActionList = mHistoryActionList.get(position).split(reg)
123 | holder.actionTextView.text = if (historyActionList.size == 1) "" else historyActionList.first()
124 | holder.resultTextView.text = historyActionList.last().trim()
125 | }
126 |
127 | override fun getItemCount(): Int {
128 | return mHistoryActionList.count()
129 | }
130 |
131 | }
132 |
133 | companion object {
134 |
135 | private val ARG_HISTORY_ACTION = "history_action"
136 |
137 | fun newInstance(historyActionList: ArrayList): HistoryActionListDialogFragment {
138 | val fragment = HistoryActionListDialogFragment()
139 | val args = Bundle()
140 | args.putStringArrayList(ARG_HISTORY_ACTION, historyActionList)
141 | fragment.arguments = args
142 | return fragment
143 | }
144 | }
145 |
146 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2017 Andrius Baruckis
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
25 |
26 |
32 |
33 |
51 |
52 |
62 |
63 |
73 |
74 |
84 |
85 |
95 |
96 |
106 |
107 |
108 |
109 |
115 |
116 |
133 |
134 |
144 |
145 |
155 |
156 |
167 |
168 |
179 |
180 |
190 |
191 |
201 |
202 |
212 |
213 |
223 |
224 |
234 |
235 |
245 |
246 |
256 |
257 |
267 |
268 |
278 |
279 |
289 |
290 |
300 |
301 |
311 |
312 |
322 |
323 |
333 |
334 |
344 |
345 |
355 |
356 |
366 |
367 |
377 |
378 |
388 |
389 |
399 |
400 |
401 |
402 |
417 |
418 |
427 |
428 |
439 |
440 |
441 |
--------------------------------------------------------------------------------
/app/src/main/java/com/baruckis/calculator/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Andrius Baruckis
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.baruckis.calculator
18 |
19 | import android.app.Activity
20 | import android.os.Bundle
21 | import android.support.annotation.IdRes
22 | import android.support.v7.app.AppCompatActivity
23 | import android.support.v7.widget.AppCompatTextView
24 | import android.view.Menu
25 | import android.view.MenuItem
26 | import android.view.View
27 | import android.widget.Button
28 | import android.widget.TextView
29 | import android.widget.Toast
30 | import java.text.DecimalFormat
31 | import java.text.DecimalFormatSymbols
32 | import java.text.ParseException
33 |
34 | // Extends AppCompatActivity class and implements Listener interface from HistoryActionListDialogFragment.
35 | class MainActivity : AppCompatActivity(), HistoryActionListDialogFragment.Listener {
36 |
37 | // Than we use this function to assign button, because once done its value won't change.
38 | // Keyword by is delegate, which adds a special behaviour to a property.
39 | private val button0: Button by bind(R.id.button_0)
40 | private val button1: Button by bind(R.id.button_1)
41 | private val button2: Button by bind(R.id.button_2)
42 | private val button3: Button by bind(R.id.button_3)
43 | private val button4: Button by bind(R.id.button_4)
44 | private val button5: Button by bind(R.id.button_5)
45 | private val button6: Button by bind(R.id.button_6)
46 | private val button7: Button by bind(R.id.button_7)
47 | private val button8: Button by bind(R.id.button_8)
48 | private val button9: Button by bind(R.id.button_9)
49 |
50 | private val buttonMemoryClear: Button by bind(R.id.button_memory_clear)
51 | private val buttonMemoryRecall: Button by bind(R.id.button_memory_recall)
52 | private val buttonMemoryAdd: Button by bind(R.id.button_memory_add)
53 | private val buttonMemorySubtract: Button by bind(R.id.button_memory_subtract)
54 | private val buttonMemoryStore: Button by bind(R.id.button_memory_store)
55 |
56 | private val buttonPercentage: Button by bind(R.id.button_percentage)
57 | private val buttonRoot: Button by bind(R.id.button_root)
58 | private val buttonSquare: Button by bind(R.id.button_square)
59 | private val buttonFraction: Button by bind(R.id.button_fraction)
60 | private val buttonCE: Button by bind(R.id.button_ce)
61 | private val buttonC: Button by bind(R.id.button_c)
62 | private val buttonBackspace: Button by bind(R.id.button_backspace)
63 | private val buttonDivision: Button by bind(R.id.button_division)
64 | private val buttonMultiplication: Button by bind(R.id.button_multiplication)
65 | private val buttonSubtraction: Button by bind(R.id.button_subtraction)
66 | private val buttonAddition: Button by bind(R.id.button_addition)
67 | private val buttonEqual: Button by bind(R.id.button_equal)
68 | private val buttonPlusMinus: Button by bind(R.id.button_plus_minus)
69 | private val buttonComma: Button by bind(R.id.button_comma)
70 |
71 | private val textViewHistoryText: TextView by bind(R.id.number_history)
72 | private val textViewCurrentNumber: AppCompatTextView by bind(R.id.number_current)
73 |
74 | private var isFutureOperationButtonClicked: Boolean = false
75 | private var isInstantOperationButtonClicked: Boolean = false
76 | private var isEqualButtonClicked: Boolean = false
77 |
78 | private var currentNumber: Double = 0.0 // Value can be changed.
79 | private var currentResult: Double = 0.0
80 | private var memory: Double = 0.0
81 |
82 | private var historyText = "" // Recognize type of variable without declaring it.
83 | private var historyInstantOperationText = ""
84 | private var historyActionList: ArrayList = ArrayList()
85 |
86 | private val ZERO: String = "0" // Value cannot be changed.
87 | private val ONE: String = "1"
88 | private val TWO: String = "2"
89 | private val THREE: String = "3"
90 | private val FOUR: String = "4"
91 | private val FIVE: String = "5"
92 | private val SIX: String = "6"
93 | private val SEVEN: String = "7"
94 | private val EIGHT: String = "8"
95 | private val NINE: String = "9"
96 |
97 | private val INIT = ""
98 |
99 | private val ADDITION = " + "
100 | private val SUBTRACTION = " − "
101 | private val MULTIPLICATION = " × "
102 | private val DIVISION = " ÷ "
103 |
104 | private val PERCENTAGE = ""
105 | private val ROOT = "√"
106 | private val SQUARE = "sqr"
107 | private val FRACTION = "1/"
108 |
109 | private val NEGATE = "negate"
110 | private val COMMA = ","
111 | private val EQUAL = " = "
112 |
113 | private var currentOperation = INIT
114 |
115 |
116 | override fun onCreate(savedInstanceState: Bundle?) {
117 | super.onCreate(savedInstanceState)
118 | setContentView(R.layout.activity_main)
119 |
120 | // Kotlin gives ability to use functional programming concept - lambda expressions. Thanks to them it's possible to define only actions that we want to do instead of declaring an anonymous class every time for click listener implementation.
121 | button0.setOnClickListener {
122 | onNumberButtonClick(ZERO)
123 | }
124 |
125 | button1.setOnClickListener {
126 | onNumberButtonClick(ONE)
127 | }
128 |
129 | button2.setOnClickListener {
130 | onNumberButtonClick(TWO)
131 | }
132 |
133 | button3.setOnClickListener {
134 | onNumberButtonClick(THREE)
135 | }
136 |
137 | button4.setOnClickListener {
138 | onNumberButtonClick(FOUR)
139 | }
140 |
141 | button5.setOnClickListener {
142 | onNumberButtonClick(FIVE)
143 | }
144 |
145 | button6.setOnClickListener {
146 | onNumberButtonClick(SIX)
147 | }
148 |
149 | button7.setOnClickListener {
150 | onNumberButtonClick(SEVEN)
151 | }
152 |
153 | button8.setOnClickListener {
154 | onNumberButtonClick(EIGHT)
155 | }
156 |
157 | button9.setOnClickListener {
158 | onNumberButtonClick(NINE)
159 | }
160 |
161 | buttonAddition.setOnClickListener {
162 | onFutureOperationButtonClick(ADDITION)
163 | }
164 |
165 | buttonSubtraction.setOnClickListener {
166 | onFutureOperationButtonClick(SUBTRACTION)
167 | }
168 |
169 | buttonMultiplication.setOnClickListener {
170 | onFutureOperationButtonClick(MULTIPLICATION)
171 | }
172 |
173 | buttonDivision.setOnClickListener {
174 | onFutureOperationButtonClick(DIVISION)
175 | }
176 |
177 | buttonCE.setOnClickListener {
178 | clearEntry()
179 | }
180 |
181 | buttonC.setOnClickListener {
182 | currentNumber = 0.0
183 | currentResult = 0.0
184 | currentOperation = INIT
185 |
186 | historyText = ""
187 | historyInstantOperationText = ""
188 |
189 | textViewCurrentNumber.text = formatDoubleToString(currentNumber)
190 | textViewHistoryText.text = historyText
191 |
192 | isFutureOperationButtonClicked = false
193 | isEqualButtonClicked = false
194 | isInstantOperationButtonClicked = false
195 | }
196 |
197 | buttonBackspace.setOnClickListener {
198 |
199 | if (isFutureOperationButtonClicked || isInstantOperationButtonClicked || isEqualButtonClicked) return@setOnClickListener
200 |
201 | var currentValue: String = textViewCurrentNumber.text.toString()
202 |
203 | val charsLimit = if (currentValue.first().isDigit()) 1 else 2
204 |
205 | if (currentValue.length > charsLimit)
206 | currentValue = currentValue.substring(0, currentValue.length - 1)
207 | else
208 | currentValue = ZERO
209 |
210 | textViewCurrentNumber.text = currentValue
211 | currentNumber = formatStringToDouble(currentValue)
212 | }
213 |
214 | buttonPlusMinus.setOnClickListener {
215 |
216 | val currentValue: String = textViewCurrentNumber.text.toString()
217 |
218 | currentNumber = formatStringToDouble(currentValue)
219 | if (currentNumber == 0.0) return@setOnClickListener
220 |
221 | currentNumber *= -1
222 | textViewCurrentNumber.text = formatDoubleToString(currentNumber)
223 |
224 | if (isInstantOperationButtonClicked) {
225 | historyInstantOperationText = "($historyInstantOperationText)"
226 | historyInstantOperationText = StringBuilder().append(NEGATE).append(historyInstantOperationText).toString()
227 | textViewHistoryText.text = StringBuilder().append(historyText).append(currentOperation).append(historyInstantOperationText).toString()
228 | }
229 |
230 | if (isEqualButtonClicked) {
231 | currentOperation = INIT
232 | }
233 |
234 | isFutureOperationButtonClicked = false
235 | isEqualButtonClicked = false
236 | }
237 |
238 | buttonComma.setOnClickListener {
239 |
240 | var currentValue: String = textViewCurrentNumber.text.toString()
241 |
242 | if (isFutureOperationButtonClicked || isInstantOperationButtonClicked || isEqualButtonClicked) {
243 | currentValue = StringBuilder().append(ZERO).append(COMMA).toString()
244 | if (isInstantOperationButtonClicked) {
245 | historyInstantOperationText = ""
246 | textViewHistoryText.text = StringBuilder().append(historyText).append(currentOperation).toString()
247 | }
248 | if (isEqualButtonClicked) currentOperation = INIT
249 | currentNumber = 0.0
250 | } else if (currentValue.contains(COMMA)) {
251 | return@setOnClickListener
252 | } else currentValue = StringBuilder().append(currentValue).append(COMMA).toString()
253 |
254 | textViewCurrentNumber.text = currentValue
255 |
256 | isFutureOperationButtonClicked = false
257 | isInstantOperationButtonClicked = false
258 | isEqualButtonClicked = false
259 | }
260 |
261 | buttonEqual.setOnClickListener {
262 |
263 | if (isFutureOperationButtonClicked) {
264 | currentNumber = currentResult
265 | }
266 |
267 | val historyAllText = calculateResult()
268 |
269 | Toast.makeText(applicationContext, historyAllText, Toast.LENGTH_LONG).show()
270 |
271 | historyActionList.add(historyAllText)
272 |
273 | historyText = StringBuilder().append(formatDoubleToString(currentResult)).toString()
274 |
275 | textViewHistoryText.text = ""
276 |
277 | isFutureOperationButtonClicked = false
278 | isEqualButtonClicked = true
279 | }
280 |
281 | buttonPercentage.setOnClickListener {
282 | onInstantOperationButtonClick(PERCENTAGE)
283 | }
284 |
285 | buttonRoot.setOnClickListener {
286 | onInstantOperationButtonClick(ROOT)
287 | }
288 |
289 | buttonSquare.setOnClickListener {
290 | onInstantOperationButtonClick(SQUARE)
291 | }
292 |
293 | buttonFraction.setOnClickListener {
294 | onInstantOperationButtonClick(FRACTION)
295 | }
296 |
297 | buttonMemoryClear.isEnabled = false
298 | buttonMemoryClear.setOnClickListener {
299 |
300 | buttonMemoryClear.isEnabled = false
301 | buttonMemoryRecall.isEnabled = false
302 |
303 | memory = 0.0
304 |
305 | Toast.makeText(applicationContext, getString(R.string.memory_cleared_toast), Toast.LENGTH_SHORT).show()
306 | }
307 |
308 | buttonMemoryRecall.isEnabled = false
309 | buttonMemoryRecall.setOnClickListener {
310 |
311 | clearEntry(memory)
312 |
313 | Toast.makeText(applicationContext, getString(R.string.memory_recalled_toast), Toast.LENGTH_SHORT).show()
314 | }
315 |
316 | buttonMemoryAdd.setOnClickListener {
317 |
318 | buttonMemoryClear.isEnabled = true
319 | buttonMemoryRecall.isEnabled = true
320 |
321 | val currentValue: String = textViewCurrentNumber.text.toString()
322 | val thisOperationNumber: Double = formatStringToDouble(currentValue)
323 |
324 | val newMemory = memory + thisOperationNumber
325 |
326 | // Strings in Kotlin can include references to variables that are interpolated.
327 | // In addition to simple variable references, they can also include any expression enclosed in curly braces.
328 | // Also you can still do the string concatenation if you like using plus sign.
329 | Toast.makeText(applicationContext, getString(R.string.memory_added_toast) + "${formatDoubleToString(memory)} + ${formatDoubleToString(thisOperationNumber)} = ${formatDoubleToString(newMemory)}", Toast.LENGTH_LONG).show()
330 |
331 | memory = newMemory
332 | }
333 |
334 | buttonMemorySubtract.setOnClickListener {
335 |
336 | buttonMemoryClear.isEnabled = true
337 | buttonMemoryRecall.isEnabled = true
338 |
339 | val currentValue: String = textViewCurrentNumber.text.toString()
340 | val thisOperationNumber: Double = formatStringToDouble(currentValue)
341 |
342 | val newMemory = memory - thisOperationNumber
343 |
344 | Toast.makeText(applicationContext, getString(R.string.memory_subtracted_toast) + "${formatDoubleToString(memory)} - ${formatDoubleToString(thisOperationNumber)} = ${formatDoubleToString(newMemory)}", Toast.LENGTH_LONG).show()
345 |
346 | memory = newMemory
347 | }
348 |
349 | buttonMemoryStore.setOnClickListener {
350 |
351 | val currentValue: String = textViewCurrentNumber.text.toString()
352 | memory = formatStringToDouble(currentValue)
353 |
354 | buttonMemoryClear.isEnabled = true
355 | buttonMemoryRecall.isEnabled = true
356 |
357 | Toast.makeText(applicationContext, getString(R.string.memory_stored_toast) + formatDoubleToString(memory), Toast.LENGTH_SHORT).show()
358 | }
359 |
360 | }
361 |
362 | @Throws(IllegalArgumentException::class)
363 | private fun onNumberButtonClick(number: String, isHistory: Boolean = false) {
364 |
365 | var currentValue: String = textViewCurrentNumber.text.toString()
366 | // In Kotlin there is no more conditional operator ? : like it is in Java, which is used as a shortcut for setting a single variable to one of two states based on a single condition. Here everything can be conveniently done using if..else statement.
367 | // In Kotlin, using the equality operator == will call the equals method behind the scenes, so it's totaly acceptable to use it for string comparision.
368 | currentValue = if (currentValue == ZERO || isFutureOperationButtonClicked || isInstantOperationButtonClicked || isEqualButtonClicked || isHistory) number else StringBuilder().append(currentValue).append(number).toString()
369 |
370 | try {
371 | currentNumber = formatStringToDouble(currentValue)
372 | } catch (e: ParseException) {
373 | throw IllegalArgumentException("String must be number.")
374 | }
375 |
376 | textViewCurrentNumber.text = currentValue
377 |
378 | if (isEqualButtonClicked) {
379 | currentOperation = INIT
380 | historyText = ""
381 | }
382 |
383 | if (isInstantOperationButtonClicked) {
384 | historyInstantOperationText = ""
385 | textViewHistoryText.text = StringBuilder().append(historyText).append(currentOperation).toString()
386 | isInstantOperationButtonClicked = false
387 | }
388 |
389 | isFutureOperationButtonClicked = false
390 | isEqualButtonClicked = false
391 | }
392 |
393 | private fun onFutureOperationButtonClick(operation: String) {
394 |
395 | if (!isFutureOperationButtonClicked && !isEqualButtonClicked) {
396 | calculateResult()
397 | }
398 |
399 | currentOperation = operation
400 |
401 | if (isInstantOperationButtonClicked) {
402 | isInstantOperationButtonClicked = false
403 | historyText = textViewHistoryText.text.toString()
404 | }
405 | textViewHistoryText.text = StringBuilder().append(historyText).append(operation).toString()
406 |
407 | isFutureOperationButtonClicked = true
408 | isEqualButtonClicked = false
409 | }
410 |
411 | // Compared to switch/case statement in Java, here using when statement the argument can be literally anything, and the conditions for the branches too.
412 | // For example, Java (before version 7) does not support string in switch/case and you can achieve the desired result only by using an enum.
413 | // However in Kotlin these restrictions are gone.
414 | private fun onInstantOperationButtonClick(operation: String) {
415 |
416 | var currentValue: String = textViewCurrentNumber.text.toString()
417 | var thisOperationNumber: Double = formatStringToDouble(currentValue)
418 |
419 | currentValue = "(${formatDoubleToString(thisOperationNumber)})"
420 |
421 | when (operation) {
422 | PERCENTAGE -> {
423 | thisOperationNumber = (currentResult * thisOperationNumber) / 100
424 | currentValue = formatDoubleToString(thisOperationNumber)
425 | }
426 | // Later we use this property to find square root of the provided number.
427 | ROOT -> thisOperationNumber = thisOperationNumber.sqrt
428 | SQUARE -> thisOperationNumber = thisOperationNumber * thisOperationNumber
429 | FRACTION -> thisOperationNumber = 1 / thisOperationNumber
430 | }
431 |
432 | if (isInstantOperationButtonClicked) {
433 | historyInstantOperationText = "($historyInstantOperationText)"
434 | historyInstantOperationText = StringBuilder().append(operation).append(historyInstantOperationText).toString()
435 | textViewHistoryText.text = if (isEqualButtonClicked) historyInstantOperationText else StringBuilder().append(historyText).append(currentOperation).append(historyInstantOperationText).toString()
436 | } else if (isEqualButtonClicked) {
437 | historyInstantOperationText = StringBuilder().append(operation).append(currentValue).toString()
438 | textViewHistoryText.text = historyInstantOperationText
439 | } else {
440 | historyInstantOperationText = StringBuilder().append(operation).append(currentValue).toString()
441 | textViewHistoryText.text = StringBuilder().append(historyText).append(currentOperation).append(historyInstantOperationText).toString()
442 | }
443 |
444 | textViewCurrentNumber.text = formatDoubleToString(thisOperationNumber)
445 |
446 | if (isEqualButtonClicked) currentResult = thisOperationNumber else currentNumber = thisOperationNumber
447 |
448 | isInstantOperationButtonClicked = true
449 | isFutureOperationButtonClicked = false
450 | }
451 |
452 | private fun calculateResult(): String {
453 |
454 | when (currentOperation) {
455 | INIT -> {
456 | currentResult = currentNumber
457 | historyText = StringBuilder().append(textViewHistoryText.text.toString()).toString()
458 | }
459 | ADDITION -> currentResult = currentResult + currentNumber
460 | SUBTRACTION -> currentResult = currentResult - currentNumber
461 | MULTIPLICATION -> currentResult = currentResult * currentNumber
462 | DIVISION -> currentResult = currentResult / currentNumber
463 | }
464 |
465 | textViewCurrentNumber.text = formatDoubleToString(currentResult)
466 |
467 | if (isInstantOperationButtonClicked) {
468 | isInstantOperationButtonClicked = false
469 | historyText = textViewHistoryText.text.toString()
470 | if (isEqualButtonClicked) historyText = StringBuilder().append(historyText).append(currentOperation).append(formatDoubleToString(currentNumber)).toString()
471 | } else {
472 | historyText = StringBuilder().append(historyText).append(currentOperation).append(formatDoubleToString(currentNumber)).toString()
473 | }
474 |
475 | return StringBuilder().append(historyText).append(EQUAL).append(formatDoubleToString(currentResult)).toString()
476 | }
477 |
478 | private fun useNumberFormat(): DecimalFormat {
479 |
480 | val symbols = DecimalFormatSymbols()
481 | symbols.decimalSeparator = ','
482 |
483 | val format = DecimalFormat("#.##############")
484 | format.decimalFormatSymbols = symbols
485 |
486 | return format
487 | }
488 |
489 | private fun formatDoubleToString(number: Double): String {
490 | return useNumberFormat().format(number)
491 | }
492 |
493 | private fun formatStringToDouble(number: String): Double {
494 | return useNumberFormat().parse(number).toDouble()
495 | }
496 |
497 | // Extension property provides similar mechanism.
498 | // Note that you have to define a getter method on your property for this to work.
499 | private val Double.sqrt: Double get() = Math.sqrt(this)
500 |
501 | private fun clearEntry(newNumber: Double = 0.0) {
502 | historyInstantOperationText = ""
503 |
504 | if (isEqualButtonClicked) {
505 | currentOperation = INIT
506 | historyText = ""
507 | }
508 |
509 | if (isInstantOperationButtonClicked) textViewHistoryText.text = StringBuilder().append(historyText).append(currentOperation).toString()
510 |
511 | isInstantOperationButtonClicked = false
512 | isFutureOperationButtonClicked = false
513 | isEqualButtonClicked = false
514 |
515 | currentNumber = newNumber
516 | textViewCurrentNumber.text = formatDoubleToString(newNumber)
517 | }
518 |
519 | override fun onCreateOptionsMenu(menu: Menu?): Boolean {
520 | menuInflater.inflate(R.menu.main_menu, menu)
521 | return super.onCreateOptionsMenu(menu)
522 | }
523 |
524 | // Functions are defined using the “fun” keyword.
525 | override fun onOptionsItemSelected(item: MenuItem?): Boolean {
526 | // Safe call operator ? added to the variable before invoking the property instructs the compiler to invoke the property only if the value isn't null.
527 | when (item?.itemId) {
528 | R.id.menu_item_history -> {
529 | HistoryActionListDialogFragment.newInstance(historyActionList).show(getSupportFragmentManager(), "dialog")
530 | return true
531 | }
532 | else -> return super.onOptionsItemSelected(item)
533 | }
534 |
535 | }
536 |
537 | override fun onHistoryItemClicked(resultText: String) {
538 |
539 | try {
540 | onNumberButtonClick(resultText, true)
541 | } catch (e: IllegalArgumentException) {
542 | return
543 | }
544 |
545 | Toast.makeText(applicationContext, getString(R.string.history_result) + resultText, Toast.LENGTH_SHORT).show()
546 | }
547 |
548 | // Extension function created to add special behaviour to our Activity.
549 | // Here keyword lazy means it won’t be initialised right away but the first time the value is actually needed.
550 | fun Activity.bind(@IdRes idRes: Int): Lazy {
551 | // Function will be called only by the main thread to improve performance.
552 | return lazy(LazyThreadSafetyMode.NONE) { findViewById(idRes) }
553 | }
554 | }
--------------------------------------------------------------------------------