Introduction to Android and Kotlin

mvndy
Kotlin Thursdays
Published in
10 min readJul 6, 2018

As I near the end of the first season of Kotlin Thursdays I wanted to introduce another fun project I wanted to say thanks for sticking with me as I overhauled my life to the other side of the country.

I have decided I will run #Kotlin Thursdays in seasonal bursts. Introducing new topics with a #Kotlin team this time around. We’ll be streaming episodes starting late October to plan for better tutorials while simultaneously expanding content.

This week, we’re going to dive into a time years ago long ago when I matched with an Avocado on Tinder, who faithfully sent his avocado truth.

I will now share a years worth of avocado facts made up by someone named Avocado while we simultaneously learn about Android. As a framework, Android development can be overwhelming to look at when you’re just trying to get the basics down. I always say stick to the documentation as closely as possible and be weary of what you read on answers from StackOverflow or other sites — it will save you tears down the road, trust me. That’s not to say StackOverflow doesn’t give good tricks or that there isn’t value to StackOverflow; some answers are not always reliable, but as long as you’re armed with documentation, you’ll be able to leverage both powerfully.

(That’s just my how I felt about learning Android, but feel free to share your experiences below)

This week is an introduction to Android development with Kotlin as we create an over-glorified random fact generator. Why Kotlin and Android? Google declared Kotlin as the official language on Android in 2017. It’s expressive, concise, and powerful. Best of all, it’s interoperable with our existing Android languages and runtime.

These projects are always available on Github, which I recommend looking at to compare to your project.

Resources

Topics covered:

  • Kotlin: basic syntax, idioms, Kotlin convention. Let me know if I didn’t explain anything and I’ll be sure to answer and update!
  • Android: Project setup, Viewgroups, Components, Design vs. Text layouts, touch screen interaction
  • Android Studio: Android Virtual Device (AVD), Gradle

Gradle

Gradle is the other side of build automation systems (whereas the other is Maven, as used in TornadoFX earlier). Gradle is open-source and builds upon Apache Ant and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven for declaring project configurations.

Android Studio offers Gradle actions to be executed at the top in Build, where you can execute actions like:

  • Make… — builds the project while checking and assembling the code for compiling. In your terminal, the equivalent call may be made: ./gradlew build
  • Clean Project — simply removes the buildDir folder, thus cleaning everything including leftovers from previous builds which are no longer relevant. In your terminal, the equivalent call may be made: ./gradlew clean
  • Rebuild Project — does a clean followed by a build of your project. In your terminal, the equivalent call may be made: ./gradlew clean build which is really helpful when you need to attach the --info flag to understand why your gradle.build may not be compiling.
Gradle didn’t like my json file sitting in resources.

Android Studio will help you manage your Gradle file, so be sure your files are in sync.

Android Virtual Device Manager

It is not necessary for you to possess an Android device to be able to run an Android environment. You could always run the application on your personal Android, which tends to run significantly faster, but if you’re like me and have no room for ports I’m bound to use a virtual environment. The upper right bar contains an AVD for your use.

You will need to ensure the virtual device you use matches your SDK. When adding a device to the AVD, I went with Nexus 5 running on SDK 26 as the minimum, which may require a download the first time for the software itself.

AVD manager — be sure to use the SDK on the emulator you’re using in the project.

When you hit ‘play’ your gradle script will build and compile, and the project will run on the device of your choosing. Once you have created your project, you can quickly spin up an emulator for testing out your application.

Android Studio Overview

Android Studio is the official integrated development environment (IDE) for Google’s Android OS, but on JetBrains’ IntelliJ IDEA software and designed for the Android platform. Before Android Studio, we had Eclipse for Android development, but as its open source, the platform is free to download.

When you open a new project, call you application however you want. I named my Avocado Facts. For your first activity, just mark it a blank activity. Upon choosing the SDK, you’ll want to make sure it’s newer for Android able to use conveniently-supported features, but not so new that you are unable run your application on a majority of devices.

Include Kotlin support!

Project Studio

Let’s take a minute to go through some bells and whistles that make Android Studio more than just a fancy text editor:

In the top left corner, your default may be set to Android instead of Project. The Android view displays the project files for the quickest access to your development files, but you’re welcome to choose the editor of your preference. Project reveals all available files in your Android Project.

View ‘Project’ or ‘Android’ on the left pane
  • app: contains all the resources and raw materials that make up our application
  • app/build: contains all the files that are built for us by Android Studio. We don’t touch these files.
  • app/libs: contains any optional libraries of code we might need in our project. You don’t have to worry about this portion since we’re not importing any external libraries.
  • app/src: where the source code is stored.
  • app/src/main is where all Java/Kotlin files reside.
  • app/src/res is where all resource files exist, which concerns everything we see on the app: views, images, sound files, and more.
  • app/src/res/layouts is where we’re going to start, which contain our views.

Layouts

Layouts in Android are comprised of XML files, or eXtensible Markup Language. Android Studio allows you to use either their Design GUI or Text editor located in the lower left corner of the file view.

  • The Design view is a drag-and-drop editor that lets us visually manipulate the screen layout and displays what you see in the app. Next to the preview is the blueprint view, which gives insight into what our layout looks like behind the scenes.
  • When you compile your application, each XML layout is compiled into a view. This is represented textually with the Text view located next to Design

The right panel displays attributes for a given selected component. It’s one way to edit attributes for a certain component.

Note: This activity has been set for NoActionBar in styles.xml.

activity_main.xml — Design view

It’s up to you which is your preference for certain situations. I find both editors have its advantages over the other. I will demonstrate how you can use either. Generally, a good practice for UI is to keep your Viewgroups as shallow as possible per page.

Many attributes have GUIs for their custom options as well, such as choosing a color for your text.

Press the […] to get more Resource options.

The key is to start exploring and find what you like!

Inserting a title with Design view

Inside the Palette in the lefthand side of file editor, components are split into groups of view types to make them easier to find. Be sure to have the Component Tree open for ease of navigation. Feel free to minimize the project folder for maximum screen use for this drag-and-drop feature. All components are specialized views.

Component Tree and Palette on display to the left.

Inserting a title with Text view

One perk of using the textual view compared to the Design view is the ease of exerting control over the attributes you wish to affect. The IDE will be really helpful in guiding your best practices — follow their suggestions for cleaner code throughout. To auto-complete possible tools you might be able to use (either in .kt, .xml, .java, and more), press ctrl + [space]. Likewise, your classes will want to import its sources into your files: using alt + [enter] or clicking the yellow lightbulb will apply the IDE’s suggestions.

For string values, be sure to use component ids as a good practice. The IDE will help you properly set it up in your strings.xml file.

Here, you might notice a RelativeLayout being used as the base for our main activity: such a layout is called a ViewGroup, which is a special type of view that may hold other views. To keep my text boxes aligned evenly, I mark their width with match_parent, which it stretches to that size of the parent view, and add padding to the left and right only as dictated by android:paddingHorizontal="50dp".

  • dp stands for density-independent pixels, making this easy to resize according to the screen being used. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen.
  • sp stands for scale-independent pixels, like dp, but scaled by font size preference. Recommended mostly for font sizes.
  • There are others like mm, in, pt, and px as well.
RelativeLayout is the GroupView.

Types of ViewGroups

  • RelativeLayoutallows you to display items on a screen in relation to each other or the edges of the layouts. Easily the most flexible layout with the following options to use:
  • layout_toLeftof: the right edge position of this View is to the left of a specific View
  • layout_toRightof: the left edge position of this View is to the right of a specific View
  • layout_below: the top edge of this view is below to a specific View
  • layout_above: the bottom edge of this view is above to a specific View
  • There are other parameters that are used to place the view respect to its container:
  • layout_alignParentLeft: the left edge of this view matches the left edge of its container
  • layout_alignParentRight: the right edge of this view matches the right edge of its container
  • layout_alignParentTop: the top edge of this view matches the top edge of its container
  • layout_alignParentBottom: the bottom edge of this view matches the bottom edge of its container
  • LinearLayout — displays items in stacked order either horizontally or vertically.
  • FrameLayout — displays a dedicated single child view at a time by blocking a portion of the screen.
  • ScrollViewan extension of FrameLayout, which handles scrolling a child view containing items, or objects, on the screen.
  • ViewPagerused for managing multiple views while displaying one page at a time. ViewPager accepts an adapter and allows the user to swipe left and right to view items.
  • RecyclerViewrelated to ListView and GridView. Requires the use of a view holder design pattern for efficient item recycling. Supports the use of LayoutManager.

I also had inserted an image and another text for the main fact itself. To add an image, you need to add an image to your res/drawable folder. If you happen to load local images that are high quality, you’ll want to ensure the size of the file is not so large the memory cannot run at runtime.

Initializing the Layout View

When you compile your app, each XML layout is compiled into a view resource. You load the layout resource from your app code in your Activity.onCreate(...) callback implementation. By calling setContentView(...) which tells the activity which layout file you want to use.

Again, you can use ctrl + [space] to give suggestions to available library components.

findViewById(...) requires an id referenced as a generated resource class. When we build our project, Android automatically builds a class for us called R (resources). You can view into this generated class with app > build > generated > source > R > debug > [package.name] > R if you're curious to see where the R generates.

Generating Random Facts

You can create a random number generator to generate a random number in a give range. After doing so, we connect button logic to a pool of randomly generated facts. Using onClickListener{ ... }, our button lists for the element to be clicked or tapped. When the listener detects a click, then it runs the code given inside the function.

On the action call, the ‘random number generator’ will call an arbitrary number from 1 to 10 and one of 10 facts semi-randomly and set the textview accordingly.

CONCLUSION

That’s the basics of Android and Android Studio — I hope you found new tips to take advantage of Kotlin and certain IDE features that make coding Android a fun task. As always, there’s so much more that can build on this! Please don’t hesitate to share any you may have found, or share the ideas you could take with this project?

I’d love to set up a JSON online for the app to read, and then Avocado Guy can post his avocado wisdom on an app for all to see. Crossing my fingers he answers back.

--

--

mvndy
Kotlin Thursdays

software engineer and crocheting enthusiast. co-author of "Programming Android with Kotlin"