Home > Enterprise >  How to use Row weight modifier in a custom view?
How to use Row weight modifier in a custom view?

Time:03-30

I'm trying to make an on screen keyboard from buttons and trying to do this using a button function is kind of annoying as I can't set weights like this:

@Composable
fun MyKeyboardButton(text: String){
Button(onClick = { /*TODO*/ }, modifier = Modifier.weight(1F)) {
    Text(text = text, textAlign = TextAlign.Center)
    }
}

and then insert that into a row for each letter on a keyboard.. instead I'm stuck doing this:

Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
    Button(onClick = { /*TODO*/ }, Modifier.weight(1F)) {
        Text(text = "Q")
    }
    Button(onClick = { /*TODO*/ }, Modifier.weight(1F)) {
        Text(text = "W")

to get even spacing, which for each minor change in the code needs to then be implemented for 28 buttons.

Is there a way to add the buttons via a function? or do I need to set a button width for each for like so:

@Composable
fun MyKeyboardButton(text: String, width: Int){
Button(onClick = { /*TODO*/ }, modifier = Modifier.width(width.dp) {
Text(text = text, textAlign = TextAlign.Center)
    }
}

I would also massively appreciate examples of on screen keyboards like this if there are any..

CodePudding user response:

Modifier.weight is available inside Row because it's declared on RowScope. You can declare your composable on the same scope, so you can use weight:

@Composable
fun RowScope.MyKeyboardButton(text: String) {

Note that then you won't be able to call it outside of Row.

  • Related