Adding an Android app

We now want to create a new Gradle module in our project that will contain the Android project. You can do this by right-clicking the root package in the IDE and navigating to New | Module. We'll name this module :androidapp and, after its initial creation, it should have the following structure:

root/androidapp
build.gradle
src/main/java/com/packt/kotlinmultiplatform/MainActivity.kt
src/main/res/*
AndroidManifest.xml

The src/main/res/ directory will simply contain the default resources created by Android Studio or IntelliJ and these aren't a factor in how we will consume our shared Kotlin code.

androidapp/build.gradle is a standard Android build.gradle file as we saw previously in Chapter 13, Kotlin on Android, with one key difference. We've added a dependency to the :core module. The following code snippet demonstrates this:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 28
defaultConfig {
applicationId "com.packt.androidmultiplatform"
minSdkVersion 21
targetSdkVersion 28
...
}
...
}

dependencies {
implementation project(":core")
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.31"
...
}

The dependency on :core allows us to access the common Kotlin types, functions, and more that have been defined. We can consume those types within our Android app's code. 

Then, within our MainActivity.kt file, we can access Platform.name and use that String value to update our UI. Consider the following code for it:

// MainActivity.kt
class
MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val textView = findViewById<TextView>(R.id.textView)
textView.text = Platform.name
}
}

Once our :androidapp module is updated to consume the Platform class, we just need to update settings.gradle to recognize our new :androidapp module, as follows:

// settings.gradle
include
':core', ':androidapp'

Our Android app is now able to consume any shared code we add to the :core module. We'll look at consuming more interesting shared code later on in this chapter. For now, let's move over to iOS and see how to add and configure the iOS project.