Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
Mr. Tayyab MuGhal Avatar asked Nov 07 '19 07:11

Mr. Tayyab MuGhal


People also ask

How do I get the activity context in compose?

Create an extension function, and call this extension function with your context like context. getActivity(). Show activity on this post. Show activity on this post.

Is jetpack compose hard to learn?

Creating your first Jetpack Compose project is surprisingly easy. Just download the latest Canary version of Android studio and select a new Compose project from the list of possible Android projects. To start you'll have a simple “Hello world!” Text composable.


2 Answers

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
like image 112
Raka Adi Nugroho Avatar answered Oct 19 '22 19:10

Raka Adi Nugroho


ContextAmbient and AmbientContext has been deprecated.

You can replace them with LocalContext

Example:

val context = LocalContext.current
like image 42
Ahmed M. Abdalla Avatar answered Oct 19 '22 21:10

Ahmed M. Abdalla