Hi folks is there any way to hook View’s methods s...
# compose
l
Hi folks is there any way to hook View’s methods such as
isEnabled
to an
AbstractComposeView
? For instance I’m trying to make a Wrapper of a composable
Button
like that: My intention was to try to reuse some of the View’s API, otherwise I will have to deprecate every View’s methods so people unaware of how compose works don’t try to update the view using the View’s API Code in the 🧵
c
@leosan can you remove your code from your original message and post it in the thread instead? https://kotlinlang.slack.com/archives/CJLTWPH7S/p1616265877303000
l
Sorry @Colton Idle, sure, missed that
🖖 1
Snippet:
Copy code
class ButtonPrimary @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : AbstractComposeView(context, attrs, defStyle) {

    var text by mutableStateOf("")
    var onClickListener by mutableStateOf({})
    private var _enabled by mutableStateOf<Boolean>(true)

    @Composable
    override fun Content() {
        CanvasTheme {
            ButtonPrimary(text = text, enabled = _enabled, onClick = onClickListener)
        }
    }

    override fun isEnabled(): Boolean {
        _enabled = super.isEnabled()
        return _enabled
    }
}
The problem how to make it to invalidate/recompose the view when I call the
isEnabled= true
Copy code
findViewById<ButtonPrimary>(R.id.myButton).apply {
    text = "My Compose in XML"
    onClickListener = {
        Toast.makeText(this@HomeActivity, "Toast", Toast.LENGTH_LONG).show()
        isEnabled = false // On the first click this is set but the view is not recomposed, on the second click the view changes to the disabled state
    }
}
a
override view's
setEnabled
too and use that to write your
_enabled
property
l
Hey @Adam Powell thanks for the answer, I’ve tried that as in the snippet
Copy code
override fun isEnabled(): Boolean {
        _enabled = super.isEnabled()
        return _enabled
    }
but for some reason the view is not recomposed properly (bug maybe?)
Copy code
findViewById<ButtonPrimary>(R.id.myButton).apply {
    text = "My Compose in XML"
    onClickListener = {
        Toast.makeText(this@HomeActivity, "Toast", Toast.LENGTH_LONG).show()
        isEnabled = false // On the first click this is set but the view is not recomposed, on the second click the view changes to the disabled state
    }
}
By setting the View’s
isEnabled
to false inside the clickListener, it only updates the value to false after the second click
I meant setting the field like this
isEnabled = false
in the AbstractComposeView make
false
but in the Compose is true, the UI doesn’t reflect until the second click
nvm I wasn’t calling
setEnabled
🤦
👍 1