How to get Context in Jetpack Compose

AndroidKotlinAndroid JetpackAndroid Jetpack-Compose

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

ContextAmbient and AmbientContext is deprecated

You can replace them with

val context = LocalContext.current

Solution 3 - Android

ContextAmbient.current is deprecated as of alpha-09.

AmbientContext.current is deprecated. I think as of alpha-11.

LocalContext.current is how you get the context in a composable now.

Solution 4 - Android

The way to do this has been updated. It's now:

val context = LocalContext.current

LocalContext docs

Solution 5 - Android

ContextAmbient and AmbientContext is deprecated

Update

Now Jetpack way to do this has been updated. It's now:

val context = LocalContext.current

Solution 6 - Android

ContextAmbient.current has been deprecated, use val context = LocalContext.current instead.

Solution 7 - Android

> LocalContext.current - is the right approach. But the problem is you > can't use LocalContext.current inside @Composable function

You need to create separate function to use Context

Sample code

@Composable
fun DoneButton(){
    val context = LocalContext.current
    Button(onClick = { showToast(context,"Button clicked")}) {
        Text(name = "Done")
    }
}

fun showToast(context: Context, msg:String){
    Toast.makeText(context,msg,Toast.LENGTH_LONG).show()
}

Solution 8 - Android

For getting context in jetpack compose:

val context = ContextAmbient.current

> Working on 0.1.0-dev14

How to use it in TOAST:

@Composable
fun cardViewImplementer(item: Int) {
   val context = ContextAmbient.current
   Card(
     shape = RoundedCornerShape(10.dp),
     modifier = Modifier.padding(10.dp)
   ) {
     Box(
        modifier = Modifier
            .fillMaxWidth()
            .drawShadow(5.dp)
            .clickable(onClick = {
                Toast.makeText(context, "Clicked $item", Toast.LENGTH_SHORT).show()
            }), children = {

        })
}

For accessing the Resource:

Text("Read this string: "+context.getString(R.string.name))

Solution 9 - Android

Issues with compose_version = '1.0.0-alpha12' ? AmbientContext is now LocalContext

Solution 10 - Android

val context = LocalContext.current
Toast.makeText(context,"Hello Compose",Toast.LENGTH_LONG).show()

Solution 11 - Android

Some useful if you need get context as Activity from last Android Studio template:

val view = LocalView.current
(view.context as Activity).<activity method>

Better solution

fun Context.getActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.getActivity()
    else -> null
}

val activity = LocalContext.current.getActivity()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr. Tayyab MuGhalView Question on Stackoverflow
Solution 1 - AndroidRaka Adi NugrohoView Answer on Stackoverflow
Solution 2 - AndroidAhmed M. AbdallaView Answer on Stackoverflow
Solution 3 - AndroidmitchView Answer on Stackoverflow
Solution 4 - AndroidRyan MView Answer on Stackoverflow
Solution 5 - AndroidAnas MeharView Answer on Stackoverflow
Solution 6 - AndroidBrian MutisoView Answer on Stackoverflow
Solution 7 - AndroidRanjithkumarView Answer on Stackoverflow
Solution 8 - AndroidAli Azaz AlamView Answer on Stackoverflow
Solution 9 - AndroidGianluca VeschiView Answer on Stackoverflow
Solution 10 - Androiduser7985234View Answer on Stackoverflow
Solution 11 - AndroidbrucemaxView Answer on Stackoverflow