Kotlin Android Toast

Android Toast is used to display a sort time notification to the user without affecting the user interaction with UI. The message displayed using Toast class displays quickly, and it disappears after some time. The message in the Toast can be of type text, image or both.

To learn more about Android Toast, go to Android Toast Example

Kotlin Android Toast Example

In this example, we will display a toast message by clicking on a Button. See the following example:

  • The applicationContest returns the instance of Context class.
  • The message is of String type as ("this is toast message").
  • The Toast.LENGTH_SHORT and Toast.LENGTH_LONG are the constant defines the time duration for message display.
  • The show() method of Toast class used to display the toast message.
  • The setGravity() method of Toast used to customize the position of toast message.

activity_main.xml

Add the following code in the activity_main.xml file. In this file, we have added a button to the layout to perform a click action.

MainActivity.kt

Add the following code in the MainActivity.kt class. In this class, we are performing a click action on the button which displays the toast message.

Output:

Kotlin Android Toast Kotlin Android Toast
Next Topic#




Latest Courses