How to get Current state or context in Jetpack Compose

拈花ヽ惹草 提交于 2020-03-20 05:48:51

问题


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.


回答1:


You can access to context with define ambientContext.

Example:

val context = +ambient(ContextAmbient)



回答2:


I think your never show Toast normal way. Jetpack Compose uses a custom Kotlin compiler plugin to transform these composable functions into the app's UI elements. For example, the Text() function is defined by the Compose UI library. Jetpack Compose is in very early stages of development. You can see all repo of Jetpack compose with sample and integrations test check below link

https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/ui

For jetpack compose material demo check this link

https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/ui/ui-material/integration-tests/material-demos/src/main/java/androidx/ui/material/demos




回答3:


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

val context = ContextAmbient.current

ContextAmbient docs



来源:https://stackoverflow.com/questions/58743541/how-to-get-current-state-or-context-in-jetpack-compose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!