How to get Context in Jetpack Compose

前端 未结 7 1701
情歌与酒
情歌与酒 2021-02-19 07:35
fun createListItem(itemIndex: Int) {
Padding(left = 8.dp, right = 8.dp, top = 8.dp, bottom = 8.dp) {
    FlexRow(crossAxisAlignment = CrossAxisAlignment.Center) {
               


        
相关标签:
7条回答
  • 2021-02-19 07:37

    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))
    
    0 讨论(0)
  • 2021-02-19 07:39

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

    val context = ContextAmbient.current
    

    ContextAmbient docs

    0 讨论(0)
  • 2021-02-19 07:40

    ContextAmbient.current is deprecated as of alpha-09.

    AmbientContext.current is how you get the context in a composable.

    0 讨论(0)
  • 2021-02-19 07:50

    ContextAmbient and AmbientContext was deprecated

    Replace them with

    val context = LocalContext.current
    
    0 讨论(0)
  • 2021-02-19 07:51

    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

    0 讨论(0)
  • 2021-02-19 07:57

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

    0 讨论(0)
提交回复
热议问题