Javatpoint Logo
Javatpoint Logo

Kotlin Android Custom Toast

In the previous example, Kotlin Android Toast we display a simple toast message. We can also able to customize our message which will show as a toast. In the toast, we can display String text, image or both and customize the position of it.

Kotlin Android Custom Toast Example

In this example, we will display text and an image as a custom toast on clicking the Button.

activity_main.xml

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

custom_toast.xml

Create a layout file named as custom_toast.xml and add an ImageView and TextView to display as a toast message. Set an image to ImageView and place a message in TextView.

MainActivity.kt

In this MainActivity.kt class, we are getting the View object using the layoutInfleter.infalate() method. Clicking on the button displays the toast message with image and text. The custom layout is added over toast by calling the View using the instance of Toast class (as myToast.view = layout).

The above code performing the following tasks:

  • val myToast = Toast(applicationContext : creates the instance of Toast class.
  • myToast.duration = Toast.LENGTH_LONG: set the constant time duration to display the toast message.
  • myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0): set the gravity (position) of toast message.
  • myToast.view = layout: add the custom_toast layout to view.
  • myToast.show(): display the toast message.

Output:

Kotlin Android Custom Toast Kotlin Android Custom Toast
Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA