Table of contents |
|
Android Toast in Kotlin |
|
Creating the Screen |
|
Step 3 |
|
Step 4 |
|
Step 5 |
|
Step 6: Implementing Toast Messages in Kotlin |
|
Toast Message Display in Android |
|
Run as Emulator: |
|
A Toast is a brief notification message displayed on the Android screen for a short period. It is used to provide information to the user when certain actions are performed in the app.
ToastAndroid Toast not only involves creating a simple toast message but also includes interactive elements for the user.
To begin, we will create a screen containing an Edit Text (a text box for input) and a Button.
In Android Studio, create a new project with an empty activity and ensure that Kotlin is selected as the programming language.
In the project structure, navigate to app > res > layout > activity_main.xml. Here, we will add an Edit Text and a Button. Remove any existing TextView from the XML layout file.
|
Finally, add an Edit Text component to the layout.
app > java > com.example.toastdemo > MainActivity.kt
.toastMessage
method to the class as shown below:fun toastMessage(view: View) { val messageEditText = findViewById<EditText>(R.id.messageEditText) val message = messageEditText.text.toString() var toast = Toast.makeText(this, message, Toast.LENGTH_LONG) toast.show() }
Explanation:
text
property and stores it in the message variable.Toast.makeText() method is used to create a toast with three essential parameters:
android.app.Application
or android.app.Activity
object.We store the Toast message in a variable called toast. To make the Toast visible, we should call toast.show()
.
Step 7: Adding an OnClick Event Listener
To enable the button to display the toast message when clicked or tapped, we need to add an onClick event listener. This listener should call our toastMessage() method.
In the activity_main.xml layout file, include the following attribute in the Button element: android:onClick="toastMessage"
.
After clicking the Toast button, it is essential to hide the Android soft keyboard to ensure a clear view of the Toast message.
Function to Hide the Keyboard
fun hideKeyboard(activity: Activity) |
Locate the view by its ID and check for its existence. If found, obtain the InputMethodManager service and use it to hide the soft keyboard. |
Add the above method to the main activity class and call it before displaying the toast message.
Toast Demo