how to create calculator app in kotlin android
In this article today learn how to create calculator app in
kotlin android lets start learn tutorial.
In this program, you'll learn to
make a simple calculator using when expression in Kotlin. This calculator would
be able to add, subtract, multiply, and divide two numbers.
Android Programming with Kotlin for Beginners
- How to Create a simple Calculator App with Android Studio and Kotlin
Learn the basics of Android Studio and
programming with Kotlin.
In this course, you will create a
simple calculator app with Android Studio and Kotlin. You will learn basic
things about the android frameworks activities, fragments, and views.
Robot planning with Kotlin for Beginners. You can make a
simple computer App with Android work and Kotlin. You can learn basic things
about the robot model actions, fragments and views. Basic Model View Presenter
building, What is the action? What is the fragment? What is the perspective?
How to have a Constraint design?
Kotlin is the programming language that was made by the one
individual that produced IntelliJ thought and is fully supported by Google as
the `` first-class '' word for Android. In its system, Kotlin is very related
to Java; is solves these similar topics, it's objective oriented and statically
typed. But what's important is that Kotlin has a structure that is cleaner, it
brings more features and gets some thoughts coming from practical programming.
Swift is the programming word that was produced by Apple. It's the
general-purpose, multi-paradigm, compiled programming word that is primarily
applied for iOS, macOS, watchOS, tvOS, and Unix. Swift has been developing a
lot in the last years, it adopts good scheduling patterns and brings modern
features which makes programming simple& adaptable. Writing code is
Swift is really interactive and you will quickly make the hold of it.
Follow the full
source code how to create calculator app in kotlin android
1.MainActivity.java:
package com.javahelps.ak_kotlincalculator
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.TextView
import net.objecthunter.exp4j.ExpressionBuilder
class MainActivity : AppCompatActivity() {
// TextView used to display the input and output
lateinit var txtInput: TextView
// Represent whether the lastly pressed key is numeric or not
var lastNumeric: Boolean = false
// Represent that current state is in error or not
var stateError: Boolean = false
// If true, do not allow to add another DOT
var lastDot: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txtInput = findViewById(R.id.txtInput)
}
/**
* Append the Button.text to the TextView
*/
fun onDigit(view: View) {
if (stateError) {
// If current state is Error, replace the error message
txtInput.text = (view as Button).text
stateError = false
} else {
// If not, already there is a valid expression so append to it
txtInput.append((view as Button).text)
}
// Set the flag
lastNumeric = true
}
/**
* Append . to the TextView
*/
fun onDecimalPoint(view: View) {
if (lastNumeric && !stateError && !lastDot) {
txtInput.append(".")
lastNumeric = false
lastDot = true
}
}
/**
* Append +,-,*,/ operators to the TextView
*/
fun onOperator(view: View) {
if (lastNumeric && !stateError) {
txtInput.append((view as Button).text)
lastNumeric = false
lastDot = false // Reset the DOT flag
}
}
/**
* Clear the TextView
*/
fun onClear(view: View) {
this.txtInput.text = ""
lastNumeric = false
stateError = false
lastDot = false
}
/**
* Calculate the output using Exp4j
*/
fun onEqual(view: View) {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
val txt = txtInput.text.toString()
// Create an Expression (A class from exp4j library)
val expression = ExpressionBuilder(txt).build()
try {
// Calculate the result and display
val result = expression.evaluate()
txtInput.text = result.toString()
lastDot = true // Result contains a dot
} catch (ex: ArithmeticException) {
// Display an error message
txtInput.text = "Error"
stateError = true
lastNumeric = false
}
}
}
}
2.activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="48sp"
android:background="#efefef"
android:id="@+id/txtInput"
android:gravity="right|center_vertical"
android:maxLength="12"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="8dp"/>
<TableLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_goneMarginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtInput"
android:gravity="fill">
<TableRow
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center">
<Button
android:text="7"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnSeven"/>
<Button
android:text="8"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnEight"/>
<Button
android:text="9"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnNine"/>
<Button
android:text="/"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onOperator"
android:id="@+id/btnDivide"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center">
<Button
android:text="4"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnFour"/>
<Button
android:text="5"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnFive"/>
<Button
android:text="6"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnSix"/>
<Button
android:text="*"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onOperator"
android:id="@+id/btnMultiply"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center">
<Button
android:text="1"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnOne"/>
<Button
android:text="2"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnTwo"/>
<Button
android:text="3"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnThree"/>
<Button
android:text="-"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onOperator"
android:id="@+id/btnSubtract"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center">
<Button
android:text="."
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDecimalPoint"
android:id="@+id/btnDecimal"/>
<Button
android:text="0"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onDigit"
android:id="@+id/btnZero"/>
<Button
android:text="CLR"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onClear"
android:id="@+id/btnClear"/>
<Button
android:text="+"
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onOperator"
android:id="@+id/btnAdd"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:text="="
android:background="@drawable/button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:onClick="onEqual"
android:id="@+id/btnEqual"/>
</TableRow>
</TableLayout>
</android.support.constraint.ConstraintLayout>
3.Create a button.xml file a drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<gradient android:angle="90" android:endColor="#FFFFFF" android:startColor="#9EB8FF" android:type="linear"/>
<padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>
<size android:width="60dp" android:height="60dp"/>
<stroke android:width="1dp" android:color="#ff3da6ef"/>
</shape>
</item>
<item>
<shape>
<gradient android:angle="90" android:endColor="#FFFFFF" android:startColor="#ffd9d9d9" android:type="linear"/>
<padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>
<size android:width="60dp" android:height="60dp"/>
<stroke android:width="0.5dp" android:color="#ffcecece"/>
</shape>
</item>
</selector>
4.AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javahelps.ak_kotlincalculator" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name="com.javahelps.ak_kotlincalculator.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
5.build gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.javahelps.kotlincalculator"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'net.objecthunter:exp4j:0.4.8'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
No comments:
Post a Comment