How to create a toast in Android Kotlin

Next Story

How to navigate in Android & Kotlin

Giving user feedback throughout an android application is useful so that the user knows that they are doing the right set of actions in your application.

Let’s create a simple button that creates a toast message in this blog post.

In our Layout, let’s add a simple button.

<Button
  android:id="@+id/toast_button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="toast button" />

Now that we have a button to create a toast with, let’s add a reference to the button in our activity.

class MainActivity : AppCompatActivity() {
  private lateinit var toastButton: Button

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    toastButton = findViewById(R.id.toast_button)
    toastButton.setOnClickListener { view: View -> 
      // add toast message here
    }
  }
}

What we just did in the above code is that we added the button for creating a toast. We also added a click listener which will be populated in a second.

The click listener activates the set of code inside of it when a user taps the button.

Add the below toast function after the *add toast message here* comment.

Toast.makeText(this,
  "toast message for user goes here",
  Toast.LENGTH_SHORT)
.show()

In the above code, a toast message will be shown to the user when the user taps the button. The toast message can be customized as it fits your application.

https://www.googletagmanager.com/gtag/js?id=UA-63695651-4