Search code examples
androidkotlinanko

is there a way to use Anko commons in the fragment?


enter image description here

I am trying to call toast{..} function using Anko library. It is simple calling the toast{...} function in activity, but I can't find a way to call the function inside fragment.

so, is there a way to use Anko commons in the fragment ?


Solution

  • If you go through the documentation of Anko toast{..}, its implementation is:

    /**
     * Display the simple Toast message with the [Toast.LENGTH_SHORT] duration.
     *
     * @param message the message text resource.
     */
    
    inline fun Context.toast(message: Int): Toast = Toast
            .makeText(this, message, Toast.LENGTH_SHORT)
            .apply {
                show()
            }
    

    The toast{..} is an extension function for the Context class. Hence, it can be called from only that class which inherits from Context class.

    So, to use toast{...} in your fragment you will have to use activity?.toast("YOUR_TOAST_MESSAGE_HERE").