从AlertDialog读取尺寸值并实现新增尺寸时自动累加价格
Got it, let's work through this problem together—since you mentioned AlertDialog, I'll assume we're talking about Android here. Here's a clean, scalable approach to handle size selection with automatic price accumulation:
First, create a simple data class to tie each size to its price. This makes it super easy to add new sizes later without rewriting core logic:
data class SizeOption(val label: String, val price: Int) // Initialize your size-price list—add new sizes here anytime! val sizeOptions = listOf( SizeOption("small", 10), SizeOption("medium", 20), SizeOption("large", 30) )
We'll use a multi-choice dialog so users can select multiple sizes, with real-time price calculation as they toggle options:
var totalPrice = 0 val selectedSizes = mutableSetOf<String>() // Tracks selected sizes to avoid duplicate calculations AlertDialog.Builder(context) .setTitle("Choose Your Sizes") .setMultiChoiceItems( // Convert size labels to an array for the dialog sizeOptions.map { it.label }.toTypedArray(), null // Pass a boolean array here if you want default selected options ) { _, which, isChecked -> val selectedOption = sizeOptions[which] when (isChecked) { true -> { selectedSizes.add(selectedOption.label) totalPrice += selectedOption.price } false -> { selectedSizes.remove(selectedOption.label) totalPrice -= selectedOption.price } } // Update the dialog to show real-time total price (dialog as AlertDialog).setMessage("Current Total: $$totalPrice") } .setPositiveButton("Confirm") { _, _ -> // Handle the final selection—send to your checkout logic, etc. Toast.makeText( context, "Selected Sizes: $selectedSizes | Total: $$totalPrice", Toast.LENGTH_SHORT ).show() } .setNegativeButton("Cancel", null) .show()
The best part? Adding a new size is trivial—just append a new SizeOption to the sizeOptions list. For example:
val sizeOptions = listOf( SizeOption("small", 10), SizeOption("medium", 20), SizeOption("large", 30), SizeOption("extra-large", 45) // New size added in 1 line! )
No changes needed to the dialog logic—it'll automatically pick up the new size and price, and handle accumulation correctly.
Quick Notes
- We use a
mutableSetforselectedSizesto prevent accidental duplicate additions/removals if a user taps the same option multiple times. - The dialog's message updates in real-time, so users can see their total as they select options.
- If you need a single-selection dialog (instead of multi-select), swap
setMultiChoiceItemswithsetSingleChoiceItemsand resettotalPriceeach time an option is selected.
内容的提问来源于stack exchange,提问作者Merry Joy

