Using Kotlin Android Extensions and avoid the "Unresolved reference: kotlinx" problem

Developing Android apps using the JVM language Kotlin (by Jetbrains) is widely supported and a nice alternative to Java. Kotlin provides some syntactic sugar to make things easier. One of those blessings is the Kotlin Android Extension that helps to write clean code and to avoid boilerplate Code.

The Kotlin Android Extensions

As described by the tutorial the Kotlin Android Extensions or short kotlinx provide a simple way to access all Android Layout elements defined in the view. That means you can access any element from the current activity without using the findViewById() function. The biggest advantage: No Annotations needed.
As there are often problems to correctly add kotlinx to a project I will describe it below.

Configure kotlinx for your Android project

The further description is based on using Gradle but the same can be accomplished using any other build tool like maven. Android Extensions is a part of the Kotlin IDEA plugin. You do not need to install additional plugins.
After you added the dependency and activated the kotlinx plugin you can import the view parts. As described by Jetbrain it is convenient to import all widget properties for a specific layout in one go:

import kotlinx.android.synthetic.main.<layout>.*

Adding the Dependency

Assuming you have already configured your Android project to work with the Android Kotlin Plugin, you just have to add a single dependency to your workspaces build.gradle. I would recommend to use a parameter to synchronize the versions of the imported dependencies:

buildscript {
//kotlin plugin version to reference later
ext.kotlin_version = '1.1.2-4'

repositories {
[...]
}

dependencies {
[...]
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}

Activate the plugin

After correctly importing the dependency, all you need is to enable kotlinx in your project-local build.gradle file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'


[..]

 

{{ message }}

{{ 'Comments are closed.' | trans }}