Toasts are such a useful tool when developing an application, especially when learning a new language, that we're going to revisit the Toast. This recipe will show you the Kotlin way of displaying the very familiar Toast, as shown here:
Create a new project in Android Studio and call it KotlinToast
. Use the default Phone & Tablet
options and select Empty Activity
when prompted for the Activity Type.
Remember to check the Include Kotlin support
checkbox in the Create Android Project
dialog.
We'll keep this simple by using the default Toast layout and focus on the Kotlin code. Start by opening activity_main.xml
and follow these steps:
- Replace the existing
<TextView>
element with a<Button>
as follows:
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:onClick="showToast" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf...