androidkotlinandroid-jetpackandroid-jetpack-compose

How to get Context in Jetpack Compose


I am trying to show a Toast message when I click on the item, but how do I get the context to pass the Toast class?

fun createListItem(itemIndex: Int) {
    Padding(left = 8.dp, right = 8.dp, top = 8.dp, bottom = 8.dp) {
        FlexRow(crossAxisAlignment = CrossAxisAlignment.Center) {
            expanded(1.0f) {
                Text("Item $itemIndex")
            }
            inflexible {
                Button(
                    "Button $itemIndex",
                    style = ContainedButtonStyle(),
                    onClick = {
                        Toast.makeText(
                            this@MainActivity,
                            "Item name $itemIndex",
                            Toast.LENGTH_SHORT
                        ).show()
                    })
            }
        }
    }
}

Solution

  • Update March 2021: The previous answer has been deprecated. You should now use:

    val context = LocalContext.current
    

    Previous answer for reference:

    You can access to context with define ambientContext.

    Example:

    val context = ContextAmbient.current