152

I am trying to try out Kotlin and the Kotlin Android extensions in Android Studio. I have tried this both in Android Studio v 1.5.1 on Ubuntu 14.04, and in Android Studio v 1.5.1 on OS X El Capitan with the same result.

Here is what I am doing:

  1. I install the Kotlin plugin 1.0.0-beta-35950-IJ141-11
  2. Create a new blank Android project
  3. Convert the MainActivity file to Kotlin (via help->findaction->convert file to kotlin)
  4. Configure the project for Kotlin

I then go into the generated content_main.xml file and add an id (hello) for the "Hello World!" TextView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.gmail.npnster.mykotlinfirstproject.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/hello"
        />
</RelativeLayout>  

Then in the converted MainActivity I add a line to set the TextView. (shown below). Android Studio then prompts me (via alt-enter) to insert this line (also shown below)

import kotlinx.android.synthetic.main.content_main.*

So at this point everything seems fine

but then when I try to compile this I get

Unresolved reference: kotlinx
Unresolved reference: kotlinx
Unresolved reference: hello

Notice that I did not install the Kotlin Android extensions plugin. As of a couple of days ago this is now supposed to be included in the main plug in and is marked as obsolete. (In fact if you try to install it when you have the latest plugin, nothing new is installed)

Anyone see what I am doing wrong?

MainActivity

import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.content_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)
        print("setting text view value to hey")
        hello.text = "hey"

        val fab = findViewById(R.id.fab) as FloatingActionButton
        fab.setOnClickListener { view -> Snackbar.make(view, "Replace this with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show() }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item.itemId

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true
        }

        return super.onOptionsItemSelected(item)
    }
}
nPn
  • 16,254
  • 9
  • 35
  • 58
  • My solution was completely different, I removed the Kotlin language support as official from gradle.properties file and it worked again. Actually, the file got corrupted and has some random strings, I fixed it by going back to random strings. – Lalit Fauzdar Mar 23 '20 at 21:08

21 Answers21

265

Add kotlin-android-extensions in our buildscript's dependencies:

1. In your project-level build.gradle

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

and apply the kotlin-android-extensions plugin:

2. In your module-level build.gradle

apply plugin: 'kotlin-android-extensions'
aga
  • 27,954
  • 13
  • 86
  • 121
  • 1
    That's what I did but I still get the issue with 1.0.0-beta-3595 :( – E-Kami Dec 13 '15 at 00:31
  • Does not work for me either (1.0.0-beta-4589) - any solution yet? Just added a comment to the ticket in the bug tracker. – Steffen Funke Jan 21 '16 at 09:45
  • 11
    I also had this issue on 1.0.0-beta-4589. You also have to add `apply plugin: 'kotlin-android-extensions'` to your build.gradle file – Kio Krofovitch Feb 04 '16 at 20:39
  • 1
    Better expressed with a $kotlin_version variable: `compile "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"` – KarolDepka Mar 02 '16 at 01:00
  • 1
    Also note if you fullfill this anwer, the invalidate caches/restart may help – Beloo Jun 15 '18 at 11:46
  • Does not work for me. I'm using AS 3.1.3 and Gradle 3.1.3 (Both latest as of July 2018). The project was recently upgraded to this config, and the unresolved reference started coming for a few Kotlin lines(one was removeOnGlobalLayoutListener). Been stuck on this for 5 days. Anyone know a solution? – Shashank Saxena Jul 23 '18 at 09:42
  • Does not work for me either. I'm having this issue after upgrading to Android Studio 3.3 (used to work with 3.2). – hardysim Jan 16 '19 at 14:34
  • @hardysim and why exactly is this is a reason to give me a downvote for the solution which worked for 167 other users (at least accordingly to the number of upvotes)? – aga Jan 16 '19 at 17:23
  • @aga maybe it's a thin line between "not correct (for me) so not useful" (downvote) and "not correct (for me) but maybe useful for others" (no vote). plus, this should work without adding `kotlin-android-extensions` to the classpath (as it used to). But fine, I'm going to not use the downvote again anywhere if it's not obviously incorrect. Sorry for the inconvenience. – hardysim Jan 17 '19 at 07:44
  • How to apply it to bazel? – Anthony Kong Nov 12 '20 at 12:21
  • 3
    The 'kotlin-android-extensions' Gradle plugin is deprecated. Please use this migration guide (https://goo.gle/kotlin-android-extensions-deprecation) to start working with View Binding (https://developer.android.com/topic/libraries/view-binding) and the 'kotlin-parcelize' plugin. – Sergey Shamanayev Dec 30 '20 at 14:15
39

When you use Android Studio 2.0 and kotlin 1.0.1-2, you will come up with the same wrong. You cann't configure kotlin android extensions in your project's build.gradle, you need to configure and kotlin android extensions in every Module's build.gradle like this:

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

buildscript {
    ext.kotlin_version = '1.0.1-2'
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0 rc2"

    defaultConfig {
        applicationId "com.dazd.kotlindemo"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
       main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

Most importantly, even through the kotlin plugin included the kotlin android extension, you also need to configure the kotlin-android-extensions in your Module's bulid.gradle like this:

...
apply plugin: 'kotlin-android-extensions'
...
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

Of course, you could configure the kotlin plugin's classpath in your project's build.gradle.

MayGodBlessYou
  • 649
  • 6
  • 19
  • 1
    In my case (Android Studio 2.1.1, kotlin 1.0.2) the "Configure kotlin in Project" action configured kotlin in project build.gradle instead of Module's build.gradle, and this helped. – Ivan Kušt Jun 06 '16 at 11:34
  • Check your `ext.kotlin_version` and add `classpath...` mentioned above in the project gradle. And add the two `apply...` to app gradle. – Alston Sep 28 '19 at 11:16
37

I can't find it in the official documentation, but you must apply the plugin by adding the following to your build.gradle file:

apply plugin: 'kotlin-android-extensions'
Maxime
  • 2,048
  • 1
  • 27
  • 38
  • Yes, I think since the `kotlin-1.0.0-beta` you need to apply the plugin, but I can't find a source for that! Thanks! – Orgmir Feb 09 '16 at 03:17
  • 2
    Note: Official documentation has been updated: https://kotlinlang.org/docs/tutorials/android-plugin.html#using-kotlin-android-extensions – Maxime Feb 20 '16 at 08:56
  • 1
    Request an edit over the accepted answer and append this info! :) – Ramon Moraes Feb 28 '16 at 01:50
  • The official documentation now shows an empty code block where the `apply plugin: 'kotlin-android-extensions'` should be. – Dielson Sales May 07 '16 at 15:30
12

The buildscript block containing the kotlin-android-extensions dependency apparently needs to be in the app-module build.gradle, not in the top-level one.

iajn
  • 151
  • 5
8

I found why mine didn't work. My blocks were misplaced and by moving the buildscript{} block before the plugins as follow I got it working:

buildscript {
    ext.kotlin_version = '1.0.0-beta-3595'
    ext.anko_version = '0.8.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.kotlin"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.anko:anko-sdk15:$anko_version"
    compile "org.jetbrains.anko:anko-support-v4:$anko_version"
}
E-Kami
  • 2,529
  • 5
  • 30
  • 50
8

Removing the following import fixed the issue for me.

import android.R
Nopx
  • 395
  • 6
  • 12
6

add apply plugin: 'kotlin-android-extensions' in app/buildgradle.

if you have already added it, try to remove it and sync gradle, when sync is complete, then add it back and Sync Gradle again. This work for me.

angryd
  • 326
  • 4
  • 8
6

The problem for me was the order in which I applied the plugins.

You must apply the kotlin-android plugin before the kotlin-android-extensions plugin

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
lbenedetto
  • 2,022
  • 1
  • 21
  • 39
6

What worked for me in Android Studio 4.2 Beta 1 in macOS big sur to add id 'kotlin-android-extensions' to plugin section in app-level build.gradle file. So that it should look as follows.

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

Then sync the project and it should work

emkarachchi
  • 750
  • 1
  • 7
  • 18
4

With jetpack you have to use:

in the build.gradle (app)

    buildFeatures {
        dataBinding true
        viewBinding true
    }

   plugins {
      id 'kotlin-parcelize'
   }

In activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout
    tools:viewBindingIgnore="false">

In MainActivity.kt

import com.example.appname.databinding.ActivityMainBinding // ActivityMain is for main_activity.xml, and so on for any other activity

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        binding.button.setOnClickListener {} // use binding.elementName
    }
}
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
1

After applying the fixes mentioned above, I had to restart Android Studio to make it work.

Dawit Abraham
  • 1,616
  • 15
  • 19
1

If you are in the year 2021 then i guess most of the solutions you see here wont be of any help to you so try this instead

  1. Go to your Module build.gradle file

  2. add id 'kotlin-android-extensions' to the plugins object {}

  3. Go to file the click on sync project with gradle files

Then go back and try to import kotlinx and that should work

1

In my case, adding:

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

at the end of the module-level build.grade fixed the issue.

m4n0
  • 29,823
  • 27
  • 76
  • 89
  • This appears to be the same as [this answer](https://stackoverflow.com/a/56551152/10871073) (but with less explanation). – Adrian Mole Sep 22 '21 at 09:25
1

Had same issue

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'
    apply plugin: "kotlin-kapt"
}

removed apply plugin: to idand restarted

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id "kotlin-kapt"
}
Samir
  • 6,405
  • 5
  • 39
  • 42
0

This is how it worked for me. When I first configured Kotlin in Project, I selected the 1.1.2-3 version instead of 1.1.2-4 and added the following line in the build.gradle app file

apply plugin: 'kotlin-android-extensions'

after that I synced the build and it worked as expected.

0

I found out that I had support for C++ and Kotlin at the same time which was causing build problems.

When starting a new project, ensure C++ support is unchecked, and Kotlin support is checked. That fixed the problem for me.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
AJ Snow
  • 1
  • 1
0

In my case, I had put the code referring the view in a companion object. How silly..

KYHSGeekCode
  • 1,068
  • 2
  • 12
  • 30
0

For me the only thing that helped was to click "File" -> "Invalidate caches / Restart..."

Uriel Frankel
  • 14,304
  • 8
  • 47
  • 69
0

in my case android studio line separator changed to CRLF( I am using macbook) windows settings. when switch to CR fix my error

Hakan Mutlu
  • 11
  • 1
  • 2
0
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

For me I just had to add id 'kotlin-android-extensions' to plugins in build.gradle(Module:AppName.app) And Sync it after that.

0

use this plug-in in your app project "Gradle script" folder in file "build.Gradle (Modules : progect_name)" : "Kotlin-android-extensions" then sync the projects.