Use Android Toast maketext effectively with Kotlin

Hey there ☺️,
Using lots of time Toast is good experience for me. But fixing the crash with Toast is much important.  I personally experienced few problems with Android Toast.makeText() by writing it again and again and when using it under Thread or Fragment may lead to crash the app. 

I create a good solution, there are many good solution also available on internet. But look at my solution to use a toast in very efficient manner

Toast has static method makeText() which takes 3 parameter Context, CharSequence and a integer.

Context may be application context or activity itself.
CharSequence is string message which we want to show.
Integer is length which accept two constant Toast.LENGTH_SHORT and Toast.LENGTH_LONG which is self explanatory.

To use Toast in efficient manner, we need to first create it's extension methods

fun Context.toast(msg: String){
    Toast.makeText(this, msg, Toast.LENGTH_SHORT)
}

fun Fragment.toast(msg: String){
    context?.toast(msg)
}

Now in activity and fragment we can use this extension method to show toast. This will handle nullable context as well.

For Example
toast("Hello World")

If you like my solution please share and comment if you have more good ideas. I will add it in post if it is more efficient with your name also.

Thanks. 
Happy Coding with Toast 😀

Comments