7

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?

Shreck Ye
  • 1,591
  • 2
  • 16
  • 32

3 Answers3

6

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

deviant
  • 3,539
  • 4
  • 32
  • 47
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()
    }

Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
wang simon
  • 31
  • 1
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)
Hanzala
  • 1,965
  • 1
  • 16
  • 43