Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65648480/anko-toast-in-android-studios-unresolved-reference-none-of-the-following-cand

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...