0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ComposeのMaterial3, 1.5.0以前で少し特殊なBottomSheetの挙動を再現する

0
Posted at

はじめに

BottomSheetを使ってる時やXMLからの置換タイミングで以下のような仕様にしたいことありませんか?
Expanded表示->下げようとしたらPartiallyExpanded->さらに下げる場合にHidden
これXMLだと簡単なんですけど、Composeで再現するのが面倒なんですよね地味に。
そもそも、skipPartiallyExpandedtrueにすればExpanded表示になるので簡単じゃんって思うじゃないですか。
でもそうは問屋が卸さないんですよ。
なぜならこれをtrueにしてると、そもそも表示の流れからPartiallyExpandedを除外するよっていうフラグなので、PartiallyExpandedを途中で挟めなくなっちゃうんですよね。

実装

じゃあどうするのかっていうと以下のようにしましょう

@Composable
fun Hoge() {
  // 絶対False
  val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
    LaunchedEffect(sheetState) {
    // snapshotFlowで現状と向き先を監視
        snapshotFlow { sheetState.currentValue to sheetState.targetValue }.collect { (current, target) ->
        // あとはしたいように
            when {
                current == SheetValue.Hidden && target == SheetValue.PartiallyExpanded -> sheetState.expand()
                current == SheetValue.Expanded && target == SheetValue.Hidden -> sheetState.partialExpand()
                else -> Unit
            }
        }
    }
}

最後に

コード見たりライブラリの内部まで毎回必ず最初に見る人からすればまあ当然って感じなんですけど、そうではない人もいるわけで、まあ自分なんですけど。
skipPartiallyExpandedで最初からExpandedにできるじゃーんでやると痛い目を見るという話ですね。
ちなみにMaterial3の1.5.0以降は開始の状態と使える状態の種類を指定できます。
ナイスですねぇ。まあ安定版は出てないんですけどね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?