Home > database >  Android compose onClick being called before click
Android compose onClick being called before click

Time:10-23

I'm having issues whit the onClick on Jetpack compose, it performs the click as soon as I run the app and after returning to this activity the button stops working. Any insights?

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val context = LocalContext.current
            linkButton("Go to text views", goTo(context, TextViewActivity::class.java))
        }
    }
}

@Composable
fun linkButton(msg: String, link: Unit) {
    Button(onClick = {
        link
    }) {
        Text(msg)
    }
}

@Preview
@Composable
fun PreviewMessageCard() {
    val context = LocalContext.current

    linkButton(
        msg = "Sample",
        link = goTo(context, TextViewActivity::class.java)
    )
}

private fun goTo(context: Context, clazz: Class<*>) {
    context.startActivity(Intent(context, clazz))
}

CodePudding user response:

You are actually calling the method at the moment you are composing the linkButton, not passing it as a callback to be called on click. And on click, it is just returning a Unit which causes the unexpected behavior.

To fix that, you should change the parameter type in your composable function to () -> Unit, which represents a function type.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val context = LocalContext.current
            linkButton("Go to text views") {
                goTo(context, TextViewActivity::class.java)
            }
        }
    }
}

@Composable
fun LinkButton(msg: String, link: () -> Unit) {
    Button(onClick = {
        link()
    }) {
        Text(msg)
    }
}
  • Related