Anko toast in android studios - Unresolved reference. None of the following candidates is applicable

1.6k views Asked by At

I'm having trouble getting a toast message to display. when I try to call it i get the following error

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun Fragment.toast(message: CharSequence): Toast defined in org.jetbrains.anko
public inline fun Fragment.toast(message: Int): Toast defined in org.jetbrains.anko
public inline fun Context.toast(message: CharSequence): Toast defined in org.jetbrains.anko
public inline fun Context.toast(message: Int): Toast defined in org.jetbrains.anko
public inline fun AnkoContext<*>.toast(message: CharSequence): Toast defined in org.jetbrains.anko
public inline fun AnkoContext<*>.toast(message: Int): Toast defined in org.jetbrains.anko

I too am new to kotlin, and a lot of my searching has turned up nothing, but I'm sure its something really simple.

The fix I found here 'receiver type mismatch' with Fragment and Anko toast hasn't helped me.

I've got these dependancies

dependencies {

...
implementation "org.jetbrains.anko:anko-commons:$anko_version"
implementation "org.jetbrains.anko:anko-design:$anko_version" // For SnackBars
implementation 'org.jetbrains.anko:anko-appcompat-v7-commons:0.10.8'
implementation "org.jetbrains.anko:anko-support.v4-commons:$anko_version"

}

and these imports

import org.jetbrains.anko.toast
import org.jetbrains.anko.support.v4.toast

What I'm struggling with kinda boils down to this

class MainActivity : AppCompatActivity() {
    toast("this toast works")
   
    class Player() {
       fun score() {
          if (x) {
              //do this
          } else {
              toast("this toast doesn't work")
          }
       }
    }
 }

and it gives me the error seen above.

everything else seems to be working the way I want it to.

I guess I'm struggling to understand why something that I imported at the top of my MainActivite.kt won't work for everything with in my .kt

2

There are 2 answers

8
SlothCoding On

Use it like this:

val toast = Toast.makeText(applicationContext, text, duration)
toast.show()

And instead of applicationContext type this@MainActivity. Another approach is to save your context as a global variable then just access it with context.toast("Hello World");

0
Mark Nashat On

Anko is deprecated. Please see this page for more information.

https://github.com/Kotlin/anko/blob/master/GOODBYE.md

and we feel it's time to say goodbye to Anko.