Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Composable in a overridden method?

I would like to draw a @Composable on a override method, like

@Composable
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    Greeting()
}

Unfortunately, I can not mark a override onKeyDown() with @Composable, since I get:

Conflicting overloads: @Composable public open fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean defined in com.example.emptycompose.MainActivity, public open fun onKeyDown(p0: Int, p1: KeyEvent!): Boolean defined in androidx.appcompat.app.AppCompatActivity

How can I use a @Composable in e.g. a override onKeyDown()?

like image 981
Edna Krabappel Avatar asked Oct 26 '25 20:10

Edna Krabappel


2 Answers

This happen when you rename your .kt file.

For example, I rename KKbutton.kt to KKButton.kt and this error happen.

Clean and rebuild fix this.

like image 189
ksc91u Avatar answered Oct 29 '25 11:10

ksc91u


@Composable can only be applied to an overriding function if the base function also has a @Composable annotation.

Whilst I'm pretty sure the provided example wouldn't work in the first place since it's an event listener (it won't be invoked in a @Composable context!), if you did have control over where the function is invoked, you could simply add the annotation:

interface Foo {
    @Composable // add this
    fun foo(): Unit
}

object Bar : Foo {
    @Composable // no error
    override fun foo(): Unit {
        Text("world, hello")
    }
}
like image 29
jason. Avatar answered Oct 29 '25 10:10

jason.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!