androidkotlinanko

All Anko references are undefined


I am completely new to android developement, so I just installed Android studio a few days ago. I created a new project with Kotlin support and an empty activity, and want to use the anko library to create a dialog.

My MainActivity.kt looks like this:

package me.example.com.test

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        b_test.setOnClickListener {
            makeDialog().show()
        }
    }
}

and I created a test_dialog.kt with the following contents:

package me.example.com.test

import org.jetbrains.anko.*

fun makeDialog() = alert("Test"){
    yesButton { toast("Oh…") }
    noButton {}
}

and to the build.gradle for the app I added the anko stuff:

implementation "org.jetbrains.anko:anko-commons:$anko_version"

// Anko Layouts
implementation "org.jetbrains.anko:anko-sdk27:$anko_version" // sdk15, sdk19, sdk21, sdk23 are also available
implementation "org.jetbrains.anko:anko-appcompat-v7:$anko_version"

// Coroutine listeners for Anko Layouts
implementation "org.jetbrains.anko:anko-sdk27-coroutines:$anko_version"
implementation "org.jetbrains.anko:anko-appcompat-v7-coroutines:$anko_version"

// Anko SQLite
implementation "org.jetbrains.anko:anko-sqlite:$anko_version"

When I first copy pasted it from their GitHub it was sdk25. I replaced it with 27 (since that was the chosen api on project creation).

And to the build.gradle for the project I added:

ext.kotlin_version = '1.3.0'
ext.anko_version='0.10.8'

Both versions have the same problem: alert, yesButton, noButton and toast in the test_dialog.kt are unresolved references.

The Kotlin version was originally different, but there was a warning (additionally to the unresolved references errors) saying something about mismatched Kotlin versions, so I changed that.

Does anyone know how to solve these unresolved references?


Solution

  • Your methods are unresolved because alert is an extension method implemented on top of some kind of context. Available methods are Context.alert Fragment.alert and AnkoContext.alert. So if you want to wrap your alert dialog in another method, it must also extend one of these three classes.

    So your makeDialog function should look something like this:

    fun Context.makeDialog() = alert("Test") {
        yesButton { toast("oh..") }
        noButton { }
    }