Search code examples
androidandroid-jetpack-composecomposable

DropDownMenu not showing when click in compose


I have an image and I want to show a dropdownMenuItem when user click in the image. I was debugging the app and I can see that the code go through the DropdownDemo method but is not showing anything.

Am I doing something wrong?

Click code:

@Composable
fun Header(currentItem: CartListItems) {
    var showDialog by remember { mutableStateOf(false) }

    Box(Modifier.fillMaxWidth()) {
        Text(modifier = Modifier.align(Alignment.TopStart),
            text = currentItem.type,
            color = colorResource(id = R.color.app_grey_dark),
            fontSize = 12.sp)
        Image(painter = painterResource(R.drawable.three_dots),
            contentDescription = "more options button",
            Modifier
                .align(Alignment.CenterEnd)
                .width(24.dp)
                .height(6.75.dp)
                .clickable(indication = null,
                    interactionSource = remember { MutableInteractionSource() },
                    onClick = {
                        showDialog = true
                    }))

        if(showDialog) {
            DropdownDemo()
            showDialog = false
        }
    }
}

Dropmenu:

@Composable
fun DropdownDemo() {
    var expanded by remember { mutableStateOf(false) }
    val items = listOf("A", "B", "C", "D", "E", "F")
    val disabledValue = "B"
    var selectedIndex by remember { mutableStateOf(0) }
    Box(modifier = Modifier
        .fillMaxSize()
        .wrapContentSize(Alignment.TopStart)) {
        Text(items[selectedIndex],modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = { expanded = true })
            .background(
                Color.Gray
            ))
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    Color.Red
                )
        ) {
            items.forEachIndexed { index, s ->
                DropdownMenuItem(onClick = {
                    selectedIndex = index
                    expanded = false
                }) {
                    val disabledText = if (s == disabledValue) {
                        " (Disabled)"
                    } else {
                        ""
                    }
                    Text(text = s + disabledText)
                }
            }
        }
    }
}

Solution

  • showDialog appears to be a MutableState object. Hence, when the image is clicked, it becomes true, and a recomposition is triggered, after which the conditional block is executed, displaying the DropDownMenu. However, in the very next line. You equate showDialog to false, re-trigerring a recomposition, and rendering the DropDownMenu collapsed.