如何在 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()
                })

        }
    }
  }
}

我试着用正常的方式做吐司。但我得到了错误我尝试了很多倍数来源但失败了。

ContextAmbientAmbientContext 已弃用

更新

现在更新了 Jetpack 执行此操作的方式。现在是:

val context = LocalContext.current

2021 年 3 月更新: 先前的答案已被弃用。您现在应该使用:

val context = LocalContext.current

上一个答案供参考:

您可以使用 define ambientContext.

访问上下文

示例:

val context = ContextAmbient.current

执行此操作的方法已更新。现在是:

val context = LocalContext.current

LocalContext docs

在 Jetpack Compose 中获取上下文:

val context = ContextAmbient.current

Working on 0.1.0-dev14

如何在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 = {

        })
}

访问资源

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

ContextAmbient.current 已弃用,请改用 val context = LocalContext.current

ContextAmbient.currentalpha-09.

起已弃用

AmbientContext.current 已弃用。我认为 alpha-11

LocalContext.current 是您现在在可组合项中获取上下文的方式。

ContextAmbientAmbientContext 已弃用

您可以将它们替换为

val context = LocalContext.current

compose_version = '1.0.0-alpha12' 有问题? AmbientContext 现在是 LocalContext

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

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

您需要创建单独的函数才能使用 Context

示例代码

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

如果您需要从上一个 Android Studio 模板获取上下文作为 Activity,一些有用的内容:

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

更好的解决方案

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

val activity = LocalContext.current.getActivity()