Jetpack Compose - Toast message

In this Jetpack compose tutorial we will learn How to create Toast in an Android application using Jetpack Compose.

To instantiate Toast we will use makeText() method 

this method takes the below parameters

  • Context which will use the current screen context,
  • Text, that will display to the user,
  • Duration, time to display message for the user.
The makeText() method returns a properly initialized Toast object.


How to display Toast
To display the toast, we will use show() method.


Context object: You need to pass the application context or the Activity context.
- Using LocalContext.current we can get the Context object.
- LocalContext.current can be used only from within a Composable function. Such as we are using it within Column() function which is a composable function. LocalContext.current cannot be used within a function which is not marked with @composable annotation.
 


package
com.compose.example

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.compose.example.ui.theme.ComposeExampleTheme

class MainActivity : ComponentActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeExampleTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainContent()
}
}
}
}
}



@Composable
fun MainContent() {
val context = LocalContext.current
Box(
contentAlignment = Alignment.Center
) {
// * Toast Sample
Button(
onClick = {
// * Toast
Toast.makeText(context,
"Hi i am toast",
Toast.LENGTH_LONG).show()
},
modifier = Modifier.align(Alignment.Center)
) {
Text(text = "Toast")
}
}
}


Toast extension function

How to show Toast message using extension function in android jetpack compose.

@Composable
fun MainContent() {
val context = LocalContext.current
Box(
contentAlignment = Alignment.Center
) {
Button(
onClick = {
// * Toast extension function
context.showToast("Hi i am extension toast",Toast.LENGTH_LONG)
},
modifier = Modifier.align(Alignment.Center)
) {
Text(text = "Toast")
}
}
}

fun Context.showToast(message: String,length: Int = Toast.LENGTH_LONG){
Toast.makeText(this, message, length).show()
}

..


GET source code on Github:

Comments