0

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))
}
7
  • 5
    Your parameter type in linkButton is wrong. You are getting a Unit but you need a () -> Unit. The way you have written it causes the goto to be called immediately in setContent. In other words, you are calling the function instead of passing it. Commented Oct 21, 2021 at 9:14
  • @momt99 so if I undestand you correctly I should change the method parameter to "fun linkButton(msg: String, link: () -> Unit)" and then call it this way? linkButton("Go to text views") { goTo(context, TextViewActivity::class.java) } Commented Oct 21, 2021 at 10:08
  • Yeah, you're right. Commented Oct 21, 2021 at 10:49
  • I've been testing that, but the goTo Method never gets called Commented Oct 21, 2021 at 11:00
  • Have you updated your linkButton method? You should call the parameter in onClick like link(). Commented Oct 21, 2021 at 11:02

1 Answer 1

1

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.