簡體   English   中英

聽 Jetpack Compose 中的 ModalBottomSheetLayout state 變化

[英]Listen ModalBottomSheetLayout state change in Jetpack Compose

目前我正在使用 ModalBottomSheetLayout 來顯示底部工作表。

不知道有沒有辦法監聽底部頁面關閉事件?

在 Compose 中偵聽更改,您需要檢查可變狀態的當前值。

如果使用ModalBottomSheetLayout你有ModalBottomSheetState ,你可以檢查這個狀態的currentValue 如果需要,您可以根據此值修改視圖狀態。

如果您想對狀態更改執行一些操作,則需要使用副作用 最基本的是LaunchedEffect ,你可以結合snapshotFlow使用它來觀察任何狀態值:

LaunchedEffect(Unit) {
    snapshotFlow { modalBottomSheetState.currentValue }
        .collect {
            println(it.toString())
        }
}

此外,我會在您第一次啟動屏幕時被調用,並且您也會在此處Hidden ,因此根據您的需要,它可能不是一個理想的解決方案。


為了在隱藏時最接近聆聽,您可以使用DisposableEffect

if (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {
    DisposableEffect(Unit) {
        onDispose {
            println("hidden")
        }
    }
}

在這里,當您的工作表出現和消失時,我將啟動DisposableEffect - 我將其從視圖層次結構中刪除,這將導致onDispose被調用。

基本上可以對狀態進行的所有操作的完整示例:

val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
val scope = rememberCoroutineScope()
LaunchedEffect(modalBottomSheetState.currentValue) {
    println(modalBottomSheetState.currentValue)
}
if (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {
    DisposableEffect(Unit) {
        onDispose {
            println("hidden")
        }
    }
}
ModalBottomSheetLayout(
    sheetState = modalBottomSheetState,
    sheetContent = {
        Text(
            "sheetContent",
            modifier = Modifier.fillMaxHeight()
        )
    }
) {
    Column {
        Text(modalBottomSheetState.currentValue.toString())
        Button(onClick = {
            scope.launch {
                modalBottomSheetState.show()
            }
        }) {
            Text("Show bottom sheet")
        }
    }
}

您可以只使用rememberModalBottomSheetState中的confirmStateChange

val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden, confirmStateChange = {
   if (it == ModalBottomSheetValue.Hidden) {
       println(it)
   }
   true
})

使用confirmStateChange將不會被調用,但是如果您使用clickable的方式自己show/hide模式 - 它似乎只在單擊稀松布或滑動時被調用。

解決此問題的一種方法是僅觀察modalBottomSheetState.targetValue ,該值將在模態在兩種不同狀態之間進行動畫處理時發生變化:

LaunchedEffect(modalBottomSheetState.targetValue) {
    if (modalBottomSheetState.targetValue == ModalBottomSheetValue.Hidden) {
        // do something when animating to Hidden state
      } else {
        // expanding
      }
}

這更接近於在調用show/hide之前調用的confirmStateChange時間。 觀察modalBottomSheetState.currentValue將在 animation 結束時發生變化,而modalBottomSheetState.targetValue將在 animation 開始之前發生變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM