androidkotlinandroid-jetpackandroid-jetpack-compose

How to get Context in Jetpack Compose


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()
                    })
            }
        }
    }
}

I try to make Toast in a normal way. but I got the error I tried a lot of multiples source but failed.


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