I need to auto scroll to selected item when I open the dropdown. If there are 20 items in my list, I selected 18th item. Now I reopen the dropdown, it should show the selected item in dropdown view. But it's not happening.I made changes by using scrollState but it's not working.
This is my code I need to auto scroll to selected item when I open the dropdown. If there are 20 items in my list, I selected 18th item. Now I reopen the dropdown, it should show the selected item in dropdown view. But it's not happening.I made changes by using scrollState but it's not working.
@Composable
fun DropDownWithLabel(
label: String, list: List<String>, previewWidth: Int = 80, expandedWidth: Int = 100,
onSelected: (Int) -> Unit, defaultSelection: Int = 0,spacerLimit:Int=80,paddingLimit:Int=0,heightValue:Int=275) {
Row {
Box(modifier = Modifier.wrapContentWidth(), contentAlignment = Alignment.Center) {
HeaderTextView(text = label, padding = paddingLimit)
}
Spacer(modifier = Modifier.width(spacerLimit.dp))
var expanded by remember { mutableStateOf(false) }
var selectedIndex by remember { mutableStateOf(defaultSelection) }
Box(modifier = Modifier
.width((previewWidth + 20).dp)
.wrapContentSize(Alignment.TopStart)) {
Column() {
Row {
Text(
list[defaultSelection],
modifier = Modifier
.width((previewWidth).dp)
.height(35.dp)
.clickable(onClick = { expanded = true }),
fontSize = 22.sp,
)
Image(
painter = painterResource(id = R.drawable.angle_down_solid),
contentDescription = "Custom Icon",
modifier = Modifier
.size(30.dp)
.padding(PaddingValues(top = 8.dp)),
colorFilter = ColorFilter.tint(primaryColor)
)
}
Divider(color = Color.Gray)
}
var scrollState = rememberScrollState()
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.width((expandedWidth + 20).dp) //
.height(heightValue.dp)
.background(Color.White)
.border(0.5.dp, Color.LightGray)
.shadow(1.dp, shape = RoundedCornerShape(1.dp))
.scrollable(state = scrollState, orientation = Orientation.Vertical),
) {
LaunchedEffect(expanded) {
CcuLog.d("sathish"," Entered in launched effect")
scrollState.animateScrollTo(selectedIndex)
scrollState.scrollTo(selectedIndex)
}
list.forEachIndexed { index, s ->
DropdownMenuItem(onClick = {
selectedIndex = index
expanded = false
onSelected(selectedIndex)
}, text = { Text(text = s, style = TextStyle(fontSize = 20.sp)) },
modifier = Modifier
.background(if (index == selectedIndex) secondaryColor else Color.White),
contentPadding = PaddingValues(10.dp)
)
}
}
}
}
}
The
DropdownMenuComposable has a dedicated parameter where you can provide ascrollState:Please update your code as follows:
Also, I am not sure if using the
LaunchedEffectwithin theDropdownMenuwill work properly. If it still doesn't work, please move theLaunchedEffectnext to theDropdownMenulike this: