Home > Enterprise >  How to create re-usable Button with jetpack compose?
How to create re-usable Button with jetpack compose?

Time:11-18

I have a reusable composable like below,

@Composable
fun CustomButton(
    text : String
){
    Button(onClick = { },
        modifier = Modifier.fillMaxWidth().height(60.dp)
        ) {
        Text(text = text)
    }
}

I am using the composable button as shown below.
How can I implement a callback for onclick function?

Column(
    modifier = Modifier
        .fillMaxWidth()
        .align(Alignment.BottomCenter)
        .padding(bottom = 32.dp)
) {
    CustomButton(text = "Get Started")
    Spacer(modifier = Modifier.size(16.dp))
    CustomButton(text = "Log In")
}

CodePudding user response:

Like this,

Button

@Composable
fun CustomButton(
    text: String,
    onClick: () -> Unit,
) {
    Button(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .height(60.dp),
    ) {
        Text(text = text)
    }
}

Usage

Column(
    modifier = Modifier
        .fillMaxWidth()
        .align(Alignment.BottomCenter)
        .padding(bottom = 32.dp)
) {
    CustomButton(text = "Get Started") {
        // Click event occurs here.
    }
    Spacer(modifier = Modifier.size(16.dp))
    CustomButton(text = "Log In") {
        // Click event occurs here.
    }
}
  • Related