Kotlin Development for Android
Kotlin Development for Android
com
Kotlin Development for Android (Create Your Own App)
by Michael J. Fordham
2017
All code displayed in this book is of my own creation. You may re-use the code for the purposes
of education and personal learning, and if you wish to republish this code, you must give
reference back to myself and this book. Any republication of this book without prior consent
from myself will result in a take-down notice being issued.
Any information found via research which isn’t my own has been referenced in the Harvard
referencing format, and must be referenced by yourselves in this way if you copy this
information down for other uses.
Kotlin is a language developed and trademarked by JetBrains. I do not suggest this book is
affiliated or endorsed by JetBrains. Any logos or images used are in accordance with JetBrains’
brand asset guidelines.
Android™ is a registered trademark of Google Inc. This book is in no way affiliated to or
endorsed by Google Inc. Any logos or images used are in accordance with Google Inc.’s brand
guidelines.
Chapter 7 – Conclusion
- Overview of skills learnt
- Source code download
Java version:
public class hello {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Kotlin version:
fun main(args : Array<String>){
println("Hello world!")
}
As you can see, the same program requires 2 less lines of code in the Kotlin variant, and does not
require you to make it in a class, being as you don’t need to necessarily. You can also see that
some steps have been shortened, like writing to the console no longer requires System.out.println
and then a semicolon at the end of the line from Java, as you can now do this with a more
straightforward println in Kotlin.
Java version:
int number = 0;
Kotlin version:
var number = 0
var nullNumber: Int?
Variables can be either mutable or immutable in Kotlin, meaning in layman’s terms whether or
not their value can be changed after they have been assigned a value. If you wish to make a
mutable (i.e. changeable) variable, you use the var keyword, and if you wish to make an
immutable (i.e. non-changeable) variable, you use the val keyword.
That’s enough for the explanation of why Kotlin is going to be a great language for you to get
your teeth into now though, as we can move on to downloading and setting up Android Studio,
so you can start building your app!
4. Inside this, scroll down to USB debugging and turn it on, you will see a confirmation
message, tap OK.
5. Note: you may also be required to turn on ‘Unknown sources’ under Security in order for
your app to be installed on your device.
Now your device is ready to be used to test your apps on. To do this, you will need to plug your
phone/tablet into your PC with a USB cable.
Now, we’ll select the target Android devices we are going to be developing for. For now, we can
leave ‘Phone and Tablet’ ticked, and you can choose the target API (Application Programming
Interface). For the duration of this book, we’ll be using ‘API 16: Android 4.1 (Jelly Bean)’. Click
Next.
Finally, we have to select what to name the activity. For now, we can leave it as the
‘MainActivity’, and have ‘Generate Layout File’, along with ‘Backwards Compatibility’ checked.
Click Finish.
Once this view has been opened, we can select KotlinHelloWorld, app, src, main, and java to
open the main activity or res, layout to open the design view of the main activity.
Once you are on the XML design view you will be presented with a screen like this:
For now though, we will only deal with the design view. On your screen you may see ‘Hello
world!’ already written. This is not the app we are building (sorry to disappoint, I know it could
be the next big thing in the Play Store), so we are going to select that component and press delete
(on your keyboard).
From here, we are going to drag a ‘Button’ onto the screen of the device. In the ‘Palette’ menu to
the left of the design, we can see we have a number of components we can use in our app. Click
the button option and drag it onto the screen.
Now we can add another component to the screen, a TextView. This will allow us to show text on
the app and also do stuff to the text when we click the button. So, now you will have to click and
drag a ‘TextView’ to the app’s screen.
Now that we have the TextView on screen, we can edit its attributes just like we could with the
button on the right side of the screen. For this, we could name it ‘lblText’ (lbl standing for label),
and change the text of it to ‘This is a test’.
Once you have done this on both sides, you should end up with the button on screen looking like
this:
That jagged line indicates a connection to both sides of the screen, and as the connection is equal
either side, the button should be centralised (this will differ on different devices occasionally as
Android Studio likes to play with you mentally, so you may have to do some fiddling with it).
Next, we will make a constraint with the bottom edge of the screen, by clicking and dragging the
bottom circle of the button to the lower edge of the screen, like so:
You can type in any value you like, or select the options from the drop-down list. We will be
selecting ‘16’ for now.
Now, we want to repeat the steps we performed for centralising the button, for the TextView, by
dragging the circles on either side to the edges of the screen. Then, we will drag the bottom circle
of the TextView to the top circle of the button, to create a constraint relationship between them.
You should end up with something like this:
Now, we can start getting down to the actual programming aspect of this application, and help
you code your first Android app.
compile "org.jetbrains.anko:anko-commons:$anko_version"
We will then replace $anko_version with the build number that Anko is currently on. At the time
of writing this book, Anko was on 0.10.1 (you can find the current version at
www.github.com/kotlin/anko), so the code would look like this:
compile "org.jetbrains.anko:anko-commons:0.10.1"
We would then paste this line of code into the build.gradle file, under the dependencies method.
There are two build.gradle files on the left panel, be sure to copy this line of code into the one
situated inside your app folder, not outside of it.
Once you are done, you will see a message at the top of your screen saying the gradle files have
been changed and a project sync is needed. On the top right of your screen there will be a button
saying ‘Sync Now’. Click that and wait for the project sync to complete. If you have done this
step correctly, there should be no errors when it finishes the gradle build.
Now we can return to the MainActivity.kt file. In here we are going to add a function named
changeText. This function will change the text of the TextView to whatever we want, when we
click the ‘Say Hello’ button.
So, in code form, the function will look like this:
fun changeText(){
btnSayHello.setOnClickListener{
lblText.setText("Hello world!")
}
}
Here you can see, we are setting an on-click listener for the button, and inside this on-click
listener, we are programming it so that it will set the text for the lblText element to ‘Hello
world!’.
package com.example.michael.kotlinhelloworld
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
fun changeText(){
btnSayHello.setOnClickListener{
lblText.setText("Hello world!")
}
}
}
The first line of the program, above, where it shows the package will be different in your version,
as it will contain the details you entered at the start when creating the Android project – it’ll most
likely be your name.
That’s it! We can now click the green play icon in the top right of the screen to run our app. In
this menu, you will see any virtual devices you’ve made, or any physical devices you have
connected to your computer. For example, I am testing with a OnePlus 3, and I’ve created a few
virtual devices before:
On the left, you can see what the app looked like when we first started it up, and on the right how
the app looks when we have clicked the ‘Say Hello’ button.
compile "org.jetbrains.anko:anko-commons:0.10.1"
Sync the project and once that has completed, we can begin our design stage.
Now what we want to do is drag a TextView onto our screen, and change the ID of the element
to lblFeedback (it will give feedback on whether we should guess higher or lower), and change
the text of this TextView to something like “Ready to go”. We want this element’s text to be
larger than usual, so in the attributes menu on the right, click ‘View all attributes’ at the bottom
of the pane. This will show you all the attributes of the element. Scroll down this list until you
find ‘textSize’ and enter the value 30sp. You should now have something which looks like this:
Next, we’ll add a Number field to the screen, just above the button. We will give this field the ID
numGuess and not set any text for it. We will, however, change the ‘textAlignment’ so that the
input appears in the centre of the field. Select ‘center’ from the list of all attributes. You should
now have something which looks like this:
Now we can begin the programming behind the game. On the next page is the source code for
the MainActivity.kt file, and after the code example I will explain what is happening, and what
specific parts of the code means.
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
var randomNum = 0
assignRandomNumber()
createListenerForButton()
}
return randomNum
}
fun assignRandomNumber(){
randomNum = generateRandomNumber()
}
fun guessNumber(){
var numberToGuess = randomNum
var userGuess: Int = Integer.parseInt(numGuess.getText().toString())
checkUserGuess(userGuess, numberToGuess)
}
fun createListenerForButton(){
btnGuess.setOnClickListener{
guessNumber()
}
}
}
This is a fully-functioning set of code for the higher or lower game. Highlighted in yellow are
some points I want to cover before we look into the functions that make up the game. Firstly, at
the top, you can see we are importing java.util.*. A star symbol usually means ‘all’ in
computing, so we are importing all of Java’s utilities, which we may need to use. We can do this
because, as I’ve mentioned before, Kotlin and Java are 100% interoperable and so anything
missing from Kotlin right now, we can pinch from Java.
The next line highlighted is a variable being initialised. This is a key thing to point out, as the
variable is outside of all the functions, but it is still in the class. This makes this variable a global
variable, and so any function can use or change its value as the program runs.
Below the variable you’ll find the onCreate method. You will see we have added two new lines
to this method, one calling the assignRandomNumber method, and one calling the
createListenerForButton method. This means when the app is run, a new random number will be
generated and there will be a listener for any button clicks.
The generateRandomNumber function returns an integer when it is called. Inside this function, a
new random object is created (Kotlin does not use the new keyword). Then, a minimum and
maximum set of variables are created. These act as the ranges in which the random number can
be generated. Next, the randomNum variable which is – as we said – the global variable, is
assigned a random number. Finally, the function returns a random number.
Next, we have the assignRandomNumber method, and this simply assigns the randomNum
variable the random number which is generated when generateRandomNumber is called.
Beneath that, we have guessNumber. This is the method that is called whenever the button is
clicked, and so it gets the numberToGuess from the global variable randomNum, and then it
finds the userGuess from the value the user has entered into the Number field in the app. We
have to turn this value into a string and then convert it back to an integer for the assignment to
work, and that is what is going on in that line of code. Finally, the method calls checkUserGuess
and gives it the parameters userGuess and numberToGuess.
The next function we have is checkUserGuess, which takes the userGuess variable, and the
numberToGuess variable, and puts them through an if statement to check if they are higher,
lower or equal to each other, and changes the text of the TextView based on that outcome.
Finally, we have the createListenerForButton function, and this simply creates an on-click
listener for the button we have on screen, and when it is clicked, the guessNumber method will
be called.
Here we are adapting the createListenerForButton method, and as you can see we first check if
the data entered in the Number field is empty, and in that case we display a toast message to the
user asking them to enter a number. A toast is a small pop-up which displays a short sentence on
the user’s screen.
We will now add another activity to our app, so we can show a more exciting ‘correct guess’
screen.
What we want to do first is right-click our layout folder, under res, and select New, Activity,
Empty Activity. We can then name the activity something like ‘CorrectGuessActivity’, and leave
‘Generate Layout File‘ and ‘Backwards Compatibility’ checked. Do not make it a ‘Launcher
Activity’.
Initially, the vertical guideline will be set up to work in pixels, rather than percentage of the
screen. You can change this by clicking the arrow in the circle until it turns to a ‘%’ sign.
Now, drag the guideline to the middle of the screen, and a 50% marker will show. You can now
add the constraints to the buttons so that they are either side of the guideline, and are connected
to either side of the screen and guideline. You should now have something like this:
This will then have the effect of enlarging the button to take up the whole width of its
constraints, like so:
Now repeat the same step with the other button so that they match. After you have done this,
give the buttons sensible IDs, like ‘btnPlayAgain’ and ‘btnExit’. Then, set the text for them to
match their functions, so one should read ‘Play Again’ and the other ‘Exit’. You should end up
with something like this:
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
I have highlighted in yellow an area where you will need to put the package name from your
second activity. You can find it by going into the code version of the
‘activity_correct_guess.xml’ file, and it will be shown on the line regarding ‘tools:context’. All
Now that we have the second activity linked in properly, we can go back to our main activity’s
Kotlin code, and perform some small adjustments.
Firstly, we want to add a new function, called ‘openCorrectGuessScreen’. This will open the
second activity for us, using an Intent. An example for this code can be seen below:
fun openCorrectGuessScreen(){
val intent = Intent("com.example.michael.higherorlower.CorrectGuessActivity")
startActivity(intent)
}
Here, we create a new intent and link it to our second activity (the package name we used
slightly earlier), and then we call a built-in function called ‘startActivity’, and pass it the
parameter which is our intent.
Next, we need something to call this function. So, where we previously had an if statement block
which changed the text of the TextView on the main activity screen to ‘higher’, ‘lower’ or
‘correct’, we will adapt it so that when the answer is correct, we call the function to open the
correct guess screen. Here’s an example of how the code would look:
I have highlighted where we have added the call to the openCorrectGuessScreen function. So
now, when we make a correct guess, it will open our second activity.
Now what we need to do is add some code to our second activity’s Kotlin file. So, open
‘CorrectGuessActivity.kt’ as we need to add functionality for the buttons we placed on screen.
Firstly, we will be adding the ‘playAgain’ function. This will allow us to – when the button is
clicked – return to the main game screen, and have another game. The code for this looks like:
fun playAgain(){
btnPlayAgain.setOnClickListener{
val intent = Intent("[YOUR MAIN ACTIVITY’S PACKAGE NAME]")
startActivity(intent)
}
}
In this function, we are setting an on-click listener for our btnPlayAgain button, and inside this
listener, we are launching the first activity again. You will see in the code above that in the Intent
parameters, I have not filled in where your main activity’s package name should be. You can
find this package name in the ‘activity_main.xml’ text code, in the same place we found the
second activity’s package name last time.
The other function we need to add is ‘exitGame’. This will allow the user to exit the game when
they click the button on the second activity’s screen. An example of this code is here:
In this function, we are setting an on-click listener for the ‘btnExit’ button. In this listener, we
have a line of code which finishes the current activity, as well as all other activities below it of
the same affinity2. This means our application should exit without jumping back to the main
activity.
Now what we need to do is call both the functions we just made from the onCreate function,
which will mean when the activity starts up, there will be on-click listeners set up to listen for
clicks, and perform their actions accordingly. To do this, we edit the onCreate function in the
following way:
playAgain()
exitGame()
}
Here you can see I have highlighted the two lines of code, which simply call the functions we
just made. That is all that is needed to give the buttons we made on our second activity’s screen
their required functionality.
We have now finished creating our Higher or Lower application. You should test your
application now to check you have not missed any steps. It is always good practice to test run
your application after each incremental change you make to your design or code, so you can
identify exactly where a problem may have occurred.
What we need to do first is create a new project in Android Studio, like we did with the other
apps we have built. Again, to save you reading a lot of content over again here, if you do not
remember how to create a project, refer to the first chapter. We will name the application
‘BMICalculator’, remain using the API 16: Android 4.1 (Jelly Bean), and we will select an
empty activity. We will also leave the first activity named ‘MainActivity’.
Ready to go? Fantastic.
The first thing to do is add this line of code to the dependencies method in your application’s
build.gradle file. Remember, the version of Anko commons may have changed since this book
published, so be sure to compile with the latest build number (which can be found here:
www.github.com/kotlin/anko):
compile "org.jetbrains.anko:anko-commons:0.10.1"
Once the project has synced, we can begin the first design stage of our application. Open the
‘activity_main.xml’ file in the Design view, as we’ll need to place some elements on-screen. We
are going to need two TextViews, two Number (Decimal) fields and a button, laid out like so:
Now, name the TextViews something like ‘lblWeight’ and ‘lblHeight’. Name the Number
(Decimal) fields ‘numWeight’ and ‘numHeight’. Name the Button ‘btnCalculateBMI’.
Now you need to add some constraints to your elements to ensure they don’t jump around the
screen. You should end up with some that look like this:
I’ll let you in on a pro-tip which sometimes saves you a lot of time. If you look at the menu
above your design, you will see an icon of two stars. This is the ‘Infer Constraints’ button, and
when you click it, Android Studio will try to sort out your constraints for you. It doesn’t always
work, but if you are getting frustrated at constraints not doing what you want them to, this may
save you a few hours/your sanity.
Now what we want to do is create another activity for our application, like we did in the last
chapter. So, right-click the layout folder user res, click New, Activity, Empty Activity. Name this
activity something like ‘BMIResultsScreen’. Click finish.
On this activity, we want to add three TextView elements, and two Buttons in this sort of format:
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
The areas highlighted show where you should switch out my package name with your package
name. The first should be your general package name, while the other should be the package
name found in the ‘tools:context’ line of your second activity’s XML code.
Now we have this step completed, we can get back to the Kotlin code.
Go back to the ‘MainActivity.kt’ file. In here we will need to add two new functions, one for
calculating the BMI based on the user input, and one to set an on-click listener for the button on
the main activity’s screen. The code for this would look like:
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
setOnClickListenerForButton()
}
return calculatedBMI
}
fun setOnClickListenerForButton(){
btnCalculateBMI.setOnClickListener{
val intent = Intent("com.example.michael.bmicalculator.BMIResultsScreen")
intent.putExtra("BMIResult", calculateBMI())
startActivity(intent)
}
}
}
Here we can see the ‘MainActivity.kt’ file’s code. I have highlighted where your code should be
different (e.g. relating to your own package names). You can see we have a function named
‘calculateBMI’. This returns a Double value (a value with decimal points), and it takes the
weight and height from the app’s Number (Decimal) fields, and then performs a calculation on
them to make the BMI value. This value is then returned. Next, we see the
‘setOnClickListenerForButton’ method. This – as the name suggests – sets an on-click listener
for the ‘btnCalculateBMI’ button. If the button is clicked, an Intent with the parameter of our
second activity’s package is run. What you’ll also notice is that we are now passing some
information from this activity to the next activity, using the Intent. We give the value we are
passing a name, and then pass the actual value. We are passing the ‘calculateBMI’ method as it
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_bmiresults_screen.*
import java.text.DecimalFormat
showBMIResult()
findBMICategory()
setExitListener()
setCheckAgainListener()
}
fun showBMIResult(){
var decFormat = DecimalFormat("#.#")
var formattedBMI = decFormat.format(getIntent().getExtras().getDouble("BMIResult"))
lblBMIResult.setText(formattedBMI.toString())
}
fun findBMICategory(){
var categoryOfBMI = "Unknown"
var resultBMI = getIntent().getExtras().getDouble("BMIResult")
fun setExitListener(){
btnExit.setOnClickListener {
this.finishAffinity()
}
}
fun setCheckAgainListener(){
btnCheckAgain.setOnClickListener{
val intent = Intent("com.example.michael.bmicalculator.MainActivity")
startActivity(intent)
}
}
}
Our first new method here is the ‘showBMIResult’ function. Here, we use a class named
DecimalFormat which helps us to only show one decimal point for our calculation. We then get
the BMI number which was calculated by the other activity by getting the extras from the Intent,
and specifying the key of the value we want. Finally, we set the text of the ‘lblBMIResult’
element to a formatted, String version of the BMI number.
The next method we have is ‘findBMICategory’. This takes the value of the BMI result from the
previous activity, and then performs an if statement to check where the user is on the spectrum.
Most of the if statement uses ranges, which are a nifty feature of Kotlin. There are a few else if
statements which have to use the older method due to the BMI model changing category at 18.5,
a floating-point number instead of an integer. Kotlin’s ranges like integers (however floating-
point ranges have been introduced in Kotlin version 1.1). When the category has been found, the
variable ‘categoryOfBMI’ is set a value and then this value is set as the ‘lblBMIResultCategory’
text.
Below this method, we have ‘setExitListener’ and ‘setCheckAgainListener’. These both set up
on-click listeners for the buttons we used in our app, similarly to what we did in the last chapter.
After you’ve implemented that code, that’s it for our third and final app, and this chapter. It is
worth me noting that even though the BMI is widely used in the world of fitness, it isn’t a sure
sign of a person’s health. A person may be very muscly, which causes them to weigh more,
which makes BMI show their BMI category as more severe than it should be. The BMI tests can
also depend on a person’s age or gender, and their lifestyle. Here we built a simple version of the
test, but if you feel like a challenge, I encourage you to investigate it more and possibly build
upon the application we’ve made already.
When you are building your application, you may wish to not only use it in portrait mode, but
also landscape mode on your device. The problem is; this whole time we have been developing
our app and applying constraints in the portrait orientation, with no thought about how it would
appear if someone changed the orientation of their screen. Thankfully, in Android Studio you can
develop your applications for different orientations.
We will be using the last app we created – the BMI calculator – as an example. So, navigate to
the ‘activity_main.xml’ file of your BMI calculator app. In this design view, we see a button in
the menu above our application’s design screen, to the right of the ‘Language’ button, looking
like this:
Click this button, and select ‘Create Landscape Variation’. When you do this, another file will
open, which reads ‘land\activity_main.xml’, indicating this is the landscape orientation version of
the main activity. You will also probably see that the elements that were perfectly placed on-
screen in portrait mode are now not-so-perfect in landscape. This means we made the right
decision to create a landscape version of our layout, as we can fix this issue!
Simply begin dragging the elements around the screen until you can see them all (note some may
not be visible as the constraints will be pushing the elements out of view). Once we can see all
the elements, we can start deciding how constraints should be put in place in order to keep our
design stable. You may find that the constraints we originally created are fine in this set up. If
that’s the case, perfect. Test your app on your device and check that it looks how you’d want it to
in the landscape orientation.
However, if the constraints we had previously are not suitable, we can remove all constraints by
clicking the button to the left of the ‘Infer Constraints’ button. This may make some elements
change their size. Don’t panic, this is normal, we just have to scale them down to the size we
desire. This is done via clicking and dragging the boxes at the corner of the element we have
selected until we are satisfied with its size. An example can be seen here:
Below is what the app looked like when tested on my test device, a OnePlus 3:
So now, if we infer constraints again, we will see that a lot of them have attached to the central
guideline. Now we should test the app again on our physical device to see how it looks. Here is
the result:
When you come to building your own app, with a view of releasing it on the Google Play Store,
or just keeping it for personal uses, you will likely want to make it unique by adding a custom
app icon. Luckily, this is fairly straightforward in Android Studio.
Firstly, we need an application icon to use. For the purpose of this tutorial, I will direct you to a
very good tool when designing Android app icons, and that is Android Asset Studio, created by
Roman Nurik of Google. Here’s a link to it: http://bit.ly/2vbmXbn
The icon I created looks like this, however feel free to make any design you like:
Save your icon with a name prefixed by ‘ic_’, as it is common practice when developing for
Android to save your icon files with that prefix. I have named my icon ‘ic_launcher’ as that is
the default name for application launcher icons. The files you download will automatically be in
a PNG format for us.
Now what you want to do is go back into Android Studio, right-click your app folder, select
New, then select Image Asset. From here a window will open showing some default app icon
settings. You want to click the ‘Image’ radio button under ‘Source Asset’, and in the path, select
the location of your image that you downloaded. Select the xxxhdpi version. Simply click next,
and you will be presented with a screen stating that you are overwriting some files. This is fine,
as this means we are replacing the old icon design with our new one. Click finish, and you’re
done. Run the app again on your test device and you will see it now has an application icon in
your menu!
You should be very proud of yourself for the effort and time you have put in to learning these
key skills, and exposing yourself to the new-ish programming language; Kotlin. From here, I
advise you to grow even more curious about the language and developing apps for Android.
There are no limits what you can achieve in the future with the invaluable skills you have just
picked up.
I very much hope you have enjoyed the book, and if you feel like you’d like to learn more of the
basics of Kotlin, you can check out my other book on Amazon – Kotlin Development for
Beginners (with Code Examples), available on Kindle and in paperback. Here’s a link:
http://bit.ly/kotlin-book
I wish you the very best of luck in the future for your next application developments.
The source code for the apps we made is available online here: http://bit.ly/2viUyzB
3. NHS. (2017). How can I work out my body mass index (BMI)? - Health questions - NHS Choices.
[online] Available at: http://www.nhs.uk/chq/Pages/how-can-i-work-out-my-bmi.aspx?
CategoryID=51&SubCategoryID=165 [Accessed 31 Jul. 2017].