Skip to content

Instantly share code, notes, and snippets.

@Pinaki93
Last active August 29, 2023 03:45
Show Gist options
  • Save Pinaki93/163f293a9c6f7ba3ae5f20bc87d133da to your computer and use it in GitHub Desktop.
Save Pinaki93/163f293a9c6f7ba3ae5f20bc87d133da to your computer and use it in GitHub Desktop.
Jetpack Compose Generic Spinner
@Composable
fun QuantityMenuSpinner(
availableQuantities: List<String>,
selectedItem: String,
onItemSelected: (String) -> Unit
) {
Spinner(
modifier = Modifier.wrapContentSize(),
dropDownModifier = Modifier.wrapContentSize(),
items = availableQuantities,
selectedItem = selectedItem,
onItemSelected = onItemSelected,
selectedItemFactory = { modifier, item ->
Row(
modifier = modifier
.padding(8.dp)
.wrapContentSize()
) {
Text(item)
Icon(
painter = painterResource(id = R.drawable.ic_baseline_arrow_drop_down_24),
contentDescription ="drop down arrow"
)
}
},
dropdownItemFactory = { item, _ ->
Text(text = item)
}
)
}
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.DropdownMenuItem
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
@Composable
fun <T> Spinner(
modifier: Modifier = Modifier,
dropDownModifier: Modifier = Modifier,
items: List<T>,
selectedItem: T,
onItemSelected: (T) -> Unit,
selectedItemFactory: @Composable (Modifier, T) -> Unit,
dropdownItemFactory: @Composable (T, Int) -> Unit,
) {
var expanded: Boolean by remember { mutableStateOf(false) }
Box(modifier = modifier.wrapContentSize(Alignment.TopStart)) {
selectedItemFactory(
Modifier
.clickable { expanded = true },
selectedItem
)
androidx.compose.material.DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = dropDownModifier
) {
items.forEachIndexed { index, element ->
DropdownMenuItem(onClick = {
onItemSelected(items[index])
expanded = false
}) {
dropdownItemFactory(element, index)
}
}
}
}
}
@yang-chao
Copy link

๐Ÿ‘

@hoyahozz
Copy link

๐Ÿ‘๐Ÿ‘๐Ÿ‘

@ArjixWasTaken
Copy link

Why is this called spinner? can anyone explain?
How is a dropdown menu a "spinner"?

this is what we traditionally call a spinner when it comes to UI
image

at least in web dev...

@osvelalvarez
Copy link

osvelalvarez commented Aug 22, 2023

Why is this called spinner? can anyone explain? How is a dropdown menu a "spinner"?
at least in web dev...

You said it, in web dev, in Android dev, this is an Spinner (a selectable dropdown)

@Pinaki93
Copy link
Author

the name has always been confusing :) I'd like to call it "indeterminable circular progress bar" ๐Ÿ˜›

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment