Home > OS >  Using style in AndroidView Compose
Using style in AndroidView Compose

Time:10-02

How can we use style property inside AndroidView in Compose? The below code snippet doesn't work.

 AndroidView(factory = { context ->
                Button(context).apply {
                     text = "Turn On"
                     style = "@style/button_style"     
                }
            })

CodePudding user response:

"@style/button_style" can only be used inside XML.

When you set styles/colors/drawables and other resources form code, you need to use R.style.button_style instead.

Also android android.widget.Button doesn't have style parameter, but you can pass it with a context into the initializer, like this:

AndroidView(factory = { context ->
    val style = R.style.GreenText
    android.widget.Button(ContextThemeWrapper(context, style), null, style).apply {
        text = "Turn On"

    }
})

UPDATE: here's a more detailed example of AndroidView usage. You can set initial values during factory, and you can update your view state depending on Compose state variables inside update block

var flag by remember { mutableStateOf(false) }
Switch(checked = flag, onCheckedChange = { flag = !flag })
AndroidView(
    factory = { context ->
        val style = R.style.GreenText
        android.widget.Button(ContextThemeWrapper(context, style), null, style).apply {
            text = "Turn On"
            // set initial text color from resources
            setTextColor(ContextCompat.getColor(context, R.color.black))
        }
    },
    update = { button ->
        // set dynamic color while updating 
        // depending on a state variable
        button.setTextColor((if (flag) Color.Red else Color.Black).toArgb())
    }
)
  • Related