简体   繁体   中英

Dynamic row width compose

I need to create a searchbar that looks like this (strictly compose): 没有文字

带文字

Now i managed to get the one without text working, but i cannot get the cancel text to show up without bugs.

For example when using constraint row and some paddings i get effect like this漏洞

link to the working code:

https://gist.github.com/piotrsedlak/d71da26299946ef6fc5125042e04a154

I also tried working with animateContentSize but that didnt really help.

I think this can be easily achieved using weight modifier. Conditionally adjust the weights and you'll get the desired effect. Here's a snippet for the same:

@Composable
fun DynamicToolbar() {
    var text by remember { mutableStateOf(TextFieldValue()) }
    val fieldWeight = if (text.text.isNotBlank()) 0.8f else 1f
    Row(modifier = Modifier.fillMaxWidth()
    ) {
        OutlinedTextField(
            value = text,
            onValueChange = { text = it },
            leadingIcon = { Icon(Icons.Default.Search, null, tint = Color.DarkGray) },
            trailingIcon = {
                if (text.text.isNotBlank()) {
                    Icon(
                        Icons.Default.Close,
                        null,
                        tint = Color.LightGray,
                        modifier = Modifier.clickable { text = text.copy("") }
                    )
                }
            },
            modifier = Modifier
                .weight(fieldWeight)
                .alignBy(FirstBaseline)
        )
        if (text.text.isNotBlank()) {
            TextButton(
                onClick = { },
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1 - fieldWeight)
                    .alignBy(FirstBaseline)
            ) {
                Text("Cancel")
            }
        }
    }
}

I'm using Compose 1.0.0-alpha11

PS: I fixed the baseline alignment problem as well (credits) . Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM