Search code examples
androidandroid-jetpack-composeandroid-button

Android Jetpack Compose - Button With Leading Drawable


I have a simple Sign In screen and I have a problem with one of my Button. I just wanted to create a button has a drawable on start with a 10dp padding-start, and has a text on center of button.

Here you an see what I did:

SignInScreen.kt:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SignInScreen(
    //navController: NavController,
    //viewModel: SignInViewModel = hiltViewModel()
) {
    Column(
        modifier = Modifier
            .padding(24.dp)
            .fillMaxSize(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.Start
    ) {
...
...
...
        ContinueWithButton(buttonText = "Google Sign In", id = R.drawable.google_icon , onClick = {  })
    }
}

And

ContinueWithButton.kt:

@Composable
fun ContinueWithButton(
    buttonText: String,
    @DrawableRes id: Int,
    onClick: () -> Unit = {},
) {
    Button(
        onClick = { onClick() },
        modifier = Modifier
            .fillMaxWidth()
            .height(36.dp),
        shape = RoundedCornerShape(12.dp),
        colors = ButtonDefaults.buttonColors(
            containerColor = Color.White,
        ),
        border = BorderStroke(1.dp, Color.Black)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth(),
            contentAlignment = Alignment.Center
        ) {
            Row(
                modifier = Modifier
                    .align(Alignment.CenterStart)
            ) {
                Image(
                    painter = painterResource(id),
                    contentDescription = buttonText,
                    modifier = Modifier.size(20.dp)
                )
            }
            Text(
                modifier = Modifier.align(Alignment.Center),
                text = buttonText,
                color = Color.Black,
                textAlign = TextAlign.Center,
                fontSize = 12.sp
            )
        }
    }
}

The result is: enter image description here

It seems good but the problem is, the icon has a 24dp margin between itself and button's left edge (The black line that I drawed is 24dp). But I want it as 10dp.

enter image description here

But I can't fix my problem. What is my mistake? Can you help please?


Solution

  • If using the Material 3 button Composable, you can use contentPadding to define the padding required.

    Button(
        contentPadding = PaddingValues(
           start = 10.dp,
        ),
    )