6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Jetpack composeでCoordinatorLayoutを実現する

Last updated at Posted at 2022-06-16

NestedScrollConnectionを使ってスクロール可能な要素をスクロールした際のコールバックを受け取って、要素の高さを計算すればOK

@Composable
fun Screen() {
    val density = LocalDensity.current
    val defaultToolBarHeight = 120.dp
    val minToolBarHeight = 48.dp
    var toolBarHeight by remember {
        mutableStateOf(defaultToolBarHeight)
    }

    val nestedScrollConnection = remember {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                val delta = available.y
                // ここでスクロールに合わせて高さを計算する
                toolBarHeight = with(density) {
                    (toolBarHeight.toPx() + delta).coerceIn(minToolBarHeight.toPx(), defaultToolBarHeight.toPx()).toDp()
                }
    
                return Offset.Zero
            }
        }
    }
    
    Column(
        modifier = Modifier.nestedScroll(nestedScrollConnection),
    ) {
        TopAppBar(
            modifier = Modifier.height(toolBarHeight)
        ) {
            // 略
        }

        // この要素をスクロールするとTopAppBarの高さが変化する
        LazyVerticalGrid(
        ) {
            // 略
        }
    
    }
}

こんな感じの構造にするとsheetContentをスワイプして消そうとすると一緒にTopAppBarの高さも変わってしまうのでContent側で上記のようにコンテンツ部分でTopAppBarを管理する必要がある

BottomSheetScaffold(
    modifier = Modifier.nestedScroll(nestedScrollConnection),
    topBar = {
        TopAppBar(
            modifier = Modifier.height(toolBarHeight)
        ) {
            // 略
        }
    },
    sheetContent = {
        Column {
            // 略
        }
    }
) {
    LazyVerticalGrid() {
        // 略
    }
}
6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?