Categories: Android

Kotlin Android ExtensionsにてUnresolved referenceと言われてしまう対策法

最近GoogleI/Oでkotlinを正式サポートということでこのビッグウェーブに乗ろうとしています。

その際に表題の件に関してわりと古い形でやり方が広まっていたっぽいのでその修正な記事。

解決策をさっさと知りたい方は下の方見ちゃって下さい。

症状

Kotlin Android Extensionsの導入方法について以下をbuild.gradleに追加するだけとよく見かける

apply plugin: 'kotlin-android-extensions'
buildscript {
    ext.kotlin_version = '1.1.2-4'
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

それで以下のように試しにインポートをして見るわけだが

import kotlinx.android.synthetic.activity_title.*

Unresolved reference: activity_title

activity_tiltleなんかしらんといわれる。

こまった。

いろいろ調べてみた

build.gradleの指定がわるいのかなぁと思い

I am testing out a basic Kotlin-based Android app based on the instructions in the "Kotlin for Android Developers" book. I am using Android Studio 2.1.1. I have the following build.grade (Project:
Kotlin Android App compilation failed with message: Unresolved reference: kot... - Stack Overflow

とかをみると

You need to move the kotlin buildscript section from your project build.grade to your module build.gradle file.

ほう。

かく場所が違うのかな。とかおおもおい、appのほうのbuild.gradleにapply pluginだとかdependenciesをうつしてみてやってみるがやはりだめ。

対策

結果、公式のKotlin Android Extensionsをみると、

Importing synthetic properties

It is convenient to import all widget properties for a specific layout in one go:
import kotlinx.android.synthetic.main.<layout>.*

Thus if the layout filename is activity_main.xml, we’d import kotlinx.android.synthetic.main.activity_main.*.

・・・・ん?!微妙にパスがちがくね!?

mainついてね?!

ということで以下に修正したら無事インポートできた。

import kotlinx.android.synthetic.main.activity_title.*

まとめ

マニュアルはちゃんと見よう!

mogmet

View Comments

  • Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  • Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  • I don't think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  • I don't think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  • Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

Share
Published by
mogmet