Where is the KTX toast extension function?
Asked Answered
P

3

8

I have learned from this article Even Sweeter Android development with Android KTX (https://www.kotlindevelopment.com/even-sweeter-android-ktx-kotlin/) that Android toast can be simplified using KTX from

Toast.makeText(context, R.string.toast_message, Toast.LENGTH_SHORT).show()

to

toast(R.string.toast_message)

I wanted to try it in my project but I couldn't find it in androidx.core:core-ktx:1.0.0. So in which dependency is this extension function?

Paxwax answered 11/1, 2019 at 7:29 Comment(1)
but i could'nt find add to app module and rename your xml to be apart of it also androidx.core:core-ktx:1.0.1Strain
P
1

Add this

api "org.jetbrains.anko:anko-commons:0.10.1"

and use it like

toast(R.string.toast_message)

or

context.toast(R.string.toast_message)
Potomac answered 11/1, 2019 at 7:41 Comment(7)
latest version is 0.10.8Agincourt
Do I need to keep androidx.core:core-ktx:1.0.0 if I use this one?Paxwax
It is safer to use safe call operator(.?) to prepare for the context being null. like context?.toast(R.string.toast_message)Delete
that uses anko. How to use it with kotlin-ktx alone?Horner
these are their arrangement and I'm also wondering why so read this github.com/Kotlin/anko#anko-coroutines-wikiPotomac
anko is deprecatedEsp
1. Anko is deprecated 2. The question was about ktx libSeamstress
S
6

Looks like Context.toast extension was removed from ktx lib https://github.com/android/android-ktx/issues/143#issuecomment-417891391

Seamstress answered 8/5, 2020 at 9:12 Comment(0)
T
2

You can add a method extension to implement, as far as I know, there is no ready-made.


    fun Context.toast(message: String, duration: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(this, message, duration).show()
    }

    fun Context.toast(@StringRes resId: Int, duration: Int = Toast.LENGTH_SHORT) {
       Toast.makeText(this, this.resources.getText(resId), duration).show()
    }

Trailblazer answered 11/1, 2019 at 7:38 Comment(0)
P
1

Add this

api "org.jetbrains.anko:anko-commons:0.10.1"

and use it like

toast(R.string.toast_message)

or

context.toast(R.string.toast_message)
Potomac answered 11/1, 2019 at 7:41 Comment(7)
latest version is 0.10.8Agincourt
Do I need to keep androidx.core:core-ktx:1.0.0 if I use this one?Paxwax
It is safer to use safe call operator(.?) to prepare for the context being null. like context?.toast(R.string.toast_message)Delete
that uses anko. How to use it with kotlin-ktx alone?Horner
these are their arrangement and I'm also wondering why so read this github.com/Kotlin/anko#anko-coroutines-wikiPotomac
anko is deprecatedEsp
1. Anko is deprecated 2. The question was about ktx libSeamstress

© 2022 - 2024 — McMap. All rights reserved.