Пример:
Ярлык: Entry1 Сумма: 1 доллар США
Ярлык: Entry2 Сумма: 2 доллара США
Если я удалю Entry1, пользовательский интерфейс обновится чтобы показать только одну запись, которая должна быть, однако пользовательский интерфейс удалит запись 2 вместо записи 1, когда я сохраняю данные в общих настройках, он показывает, что запись 2 была сохранена. И это правильно.
Только когда я ухожу с экрана и возвращаюсь, пользовательский интерфейс обновит правильную запись (Запись2)
Ниже приведен код контекста. Пожалуйста, помогите и дайте мне знать, если вы думаете, что есть лучший способ кодирования, продолжая учиться. Готов принять все возможные отзывы!
Код: Выделить всё
@Composable
fun EditScreen(navController: NavController) {
val context = LocalContext.current
val incomeEntries = remember { mutableStateListOf
() }.apply { }
val expenseEntries = remember { mutableStateListOf() }.apply { }
val showResetConfirmation = remember { mutableStateOf(false) }
val scrollState = rememberScrollState()
val focusManager = LocalFocusManager.current
Column(modifier = Modifier
.padding(start = 16.dp)
.verticalScroll(scrollState)){
IncomeEntries(context, incomeEntries)
ExpenseEntries(context, expenseEntries)
Код: Выделить всё
@Composable
fun IncomeEntries(context: Context, incomeEntries: MutableList
){
val focusManager = LocalFocusManager.current
Column(modifier = Modifier.padding()){
if (incomeEntries.isEmpty()) {
incomeEntries.addAll(getListFromPreferences(context, "incomeEntriesKey"))
}
Text(text = "Income", fontSize = 30.sp)
incomeEntries.forEachIndexed { index, incomeEntry ->
val multipleEntriesIme = if (index == incomeEntries.lastIndex) ImeAction.Done else ImeAction.Next
var label by remember { mutableStateOf(incomeEntry.label) }
var amount by remember { mutableStateOf(incomeEntry.amount) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(value = label,
onValueChange = {
newValue -> label = newValue
incomeEntries[index] = incomeEntry.copy(label = newValue)
},
singleLine = true,
keyboardOptions = KeyboardOptions(
imeAction = multipleEntriesIme
),
placeholder = {Text(text = "Label")},
modifier = Modifier
.width(160.dp)
.padding(vertical = 8.dp)
.padding(start = 10.dp)
.onFocusChanged { focusState ->
if (!focusState.isFocused) {
incomeEntries[index].label = label
}
}
)
OutlinedTextField(
value = amount,
onValueChange = { newValue ->
// Update amount directly without formatting
amount = newValue
incomeEntries[index] = incomeEntry.copy(amount = formatAsCurrency(newValue))
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = multipleEntriesIme
),
keyboardActions = KeyboardActions(
onDone = { focusManager.clearFocus() }
),
singleLine = true,
// Apply currency formatting only for display purposes
placeholder = { Text("Amount") },
modifier = Modifier
.width(160.dp)
.padding(vertical = 8.dp)
.padding(start = 10.dp)
.onFocusChanged { focusState ->
if (!focusState.isFocused) {
// When focus is lost, format the current input as currency for display
amount =
formatAsCurrency(amount.filter { it.isDigit() || it == '.' })
// Update the incomeEntries list with the formatted value for consistent display
incomeEntries[index] = incomeEntry.copy(amount = amount)
}
}
)
Spacer(modifier = Modifier.weight(1f))
if (incomeEntries.size > 1) {
IconButton(onClick = {
Log.d("entrytrack", "Index is now ${incomeEntries[index]}")
// Handle click: remove the entry or clear it
if(incomeEntries.size == 2){
focusManager.clearFocus()
incomeEntries.removeAt(index)
}
else if (incomeEntries.size > 1) {
incomeEntries.removeAt(index)
}
}) {
Icon(
imageVector = Icons.Filled.Clear,
contentDescription = "delete income",
tint = MaterialTheme.colorScheme.error
)
}
}
}
}
Код: Выделить всё
data class PayEntry(
var label: String,
var amount: String
Я предполагаю, что параметр для IncomeEntries Composable не является MutableStateList, а является неразрешенной ссылкой.
Подробнее здесь: https://stackoverflow.com/questions/783 ... g-properly