我有一个 LazyColumn ,每个项目都是一个键值对。在我的 ViewModel 中,我维护这样的地图:
private var _pairMap = mutableMapOf<String,String>().apply {
put("hello", "world")
put("sample", "app")
}
var pairMapState by mutableStateOf(_pairMap)
在我的 Activity 中,我使用了 FloatingActionButton 的 Scaffold 和具有 SwipeToDelete 可组合的 LazyColumn。我的用例是每当我单击 fab 时,应该会打开一个对话框,并且用户应该在对话框的文本字段中输入键和值。一旦用户按下对话框的“保存”按钮,这些键值对应该在我的 LazyColumn 中更新。在“保存”按钮上单击我调用以下视图模型方法:
fun addPair(key:String, value: String) {
if (key.isNotEmpty() && value.isNotEmpty()) {
_attributesMap += mutableMapOf<String,String>().apply {
put(key, value)
}
}
}
从活动中,我直接将 传递_pairMap
给可组合对象,如下所示:
@ExperimentalMaterialApi
@Composable
fun PairScreen(
pairMap: MutableMap<String, String>, // viewmodel.pairMapState is passed here
showDialog: MutableState<Boolean>,
.....
) {
Scaffold(floatingActionButton = {
FloatingActionButton(onClick = {
showDialog.value = true
}) {
Icon(imageVector = Icons.Default.Add, contentDescription = null)
}
}) { innerPadding ->
LazyColumn(contentPadding = innerPadding) {
items(pairMap.toList()) { pair ->
// deleteState will help to not delete the element but only clear the value of the swiped item.
val deleteState =
rememberDeleteState(onDelete = { onClearValue(pair.first) })
SwipeToDelete(state = deleteState) {
PairItem(pair, showDialog)
}
}
}
}
现在,当我使用此流程添加任何内容并在对话框中按“保存”时,UI 上没有任何反应。但是当我再次按下 fab 并出现对话框时,我可以在后台看到数据现在作为新条目添加到 LazyColumn 中。
我也面临另一个问题。向左滑动后,该项目仍为红色。预期的行为是该项目应该再次可见,只有 Key 存在而没有 Value。
我的 SwipeToDelete() 看起来像这样:
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeToDelete(
state: DismissState,
content: @Composable RowScope.() -> Unit
) {
SwipeToDismiss(
state = state,
directions = setOf(DismissDirection.EndToStart),
dismissThresholds = {
FractionalThreshold(0.95f)
},
background = {
val color=when(state.dismissDirection){
DismissDirection.EndToStart -> Color.Red
else -> Color.White
}
Row(
Modifier
.fillMaxSize()
.background(color)
.padding(horizontal = 20.dp),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Delete",
color = Color.White,
modifier = Modifier
.padding(end = 8.dp)
.align(Alignment.CenterVertically)
)
Icon(
Icons.Default.Delete,
contentDescription = "Delete",
tint = Color.White,
modifier = Modifier
.padding(end = 4.dp)
.align(Alignment.CenterVertically)
)
}
},
dismissContent = content
)
}
需要帮助我如何解决这个问题。以下视频中也显示了步骤: https ://drive.google.com/file/d/1Vj8wMMn4kzZS8LzuqD1jAXi0VweXce7n/view?usp=sharing