0

I decided to use an OutlinedTextField and DropdownMenu so the user can fill an amount and select a currency.

This looks pretty nice in the preview, but when this code is being run on the device (virtual or physical) the DropdownMenu is being squeezed on the right, and therefore, the dropdown menu isn't actionable anymore.

@Composable
fun Money() {
    Row() {
        Amount()
        Currency()
    }
}

@Preview
@Composable
fun Currency() {

    var mExpanded by remember { mutableStateOf(false) }

    val mCurrencies = listOf("USD", "CHF", "EUR", "MAD") //, "Hyderabad", "Bengaluru", "PUNE")

    var mSelectedText by remember { mutableStateOf("") }

    var mTextFieldSize by remember { mutableStateOf(Size.Zero) }

    val icon = if (mExpanded)
        Icons.Filled.KeyboardArrowUp
    else
        Icons.Filled.KeyboardArrowDown

    OutlinedTextField(
        value = mSelectedText,
        onValueChange = { mSelectedText = it },
        modifier = Modifier
            .fillMaxWidth()
            .onGloballyPositioned { coordinates ->
                // This value is used to assign to
                // the DropDown the same width
                mTextFieldSize = coordinates.size.toSize()
            },
        label = { Text("Currency") },
        trailingIcon = {
            Icon(icon, "contentDescription",
                Modifier.clickable { mExpanded = !mExpanded })
        }
    )

    DropdownMenu(
        expanded = mExpanded,
        onDismissRequest = { mExpanded = false },
        modifier = Modifier
            .width(with(LocalDensity.current) { mTextFieldSize.width.toDp() })
    ) {
        mCurrencies.forEach { label ->
            DropdownMenuItem(onClick = {
                mSelectedText = label
                mExpanded = false
            }) {
                Text(text = label)
            }
        }
    }
}


@Composable
fun Amount() {
    var amount by remember {
        mutableStateOf("")
    }
    OutlinedTextField(
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
        value = amount,
        onValueChange = { amount = it },
        label = { Text(text = "Amount") },
        singleLine = true,
        trailingIcon = {
            if (amount.isNotBlank())
                IconButton(onClick = { amount = "" }) {
                    Icon(
                        imageVector = Icons.Filled.Clear,
                        contentDescription = ""
                    )
                }
        }
    )
}```
raphael
  • 93
  • 8
  • Have you check [this answer](https://stackoverflow.com/a/68728525/3585796)? wrap `OutlinedTextField` with `DropdownMenu` in a `Box`. In preview it's a `Box` by default on top of the view, but in your real core you have a `Column` which makes a different layout – Phil Dukhov Jun 06 '22 at 03:30

0 Answers0