Skip to content

Instantly share code, notes, and snippets.

@Sprajapati123
Created May 6, 2025 03:14
Show Gist options
  • Select an option

  • Save Sprajapati123/d3d810dca9093c124baa4ae49accc88a to your computer and use it in GitHub Desktop.

Select an option

Save Sprajapati123/d3d810dca9093c124baa4ae49accc88a to your computer and use it in GitHub Desktop.
@Composable
fun body(){
var expanded by remember { mutableStateOf(false) }
var selectedOptionText by remember { mutableStateOf("Select Option") }
val options = listOf("Option 1", "Option 2", "Option 3")
var textFieldSize by remember { mutableStateOf(Size.Zero) } // to capture textfield size
Column{
Box(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)) {
OutlinedTextField(
value = selectedOptionText,
onValueChange = {},
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
// capture the size of the TextField
textFieldSize = coordinates.size.toSize()
}
.clickable { expanded = true },
placeholder = { Text("Select Option") },
enabled = false, // prevent manual typing
trailingIcon = {
Icon(
imageVector = Icons.Default.ArrowDropDown,
contentDescription = null
)
}
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.width(with(LocalDensity.current) { textFieldSize.width.toDp() })
) {
options.forEach { option ->
DropdownMenuItem(
text = { Text(option) },
onClick = {
selectedOptionText = option
expanded = false
}
)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment