[Android] 036. Pager

androidx.compose.foundation1.4.0でHorizontalPager/VerticalPagerが追加されていました
https://developer.android.com/jetpack/androidx/releases/compose-foundation?authuser=1
ひさびさにデベロッパーの説明だけで簡単に実装できます
※ AccompanistのPagerを使う必要はありません

デベロッパーの説明
https://developer.android.com/jetpack/compose/layouts/pager

ちょっとした罠ではじめIgnoreで確認してたのですが、Ignoreは何故かandroidx.compose.foundationが標準で取り込まれていないようでHorizontalPager/VerticalPagerが出てこなかったです
Giraffeでは何も設定しなくても使用できます
※ compose-bomは最新にしてください

デベロッパーの内容だけだと面白くないのでAndroidアプリのGoogle ToDoみたくTabと組み合わせてみます

ページ数の変更はPageStateのpageCountで変更できなくてBardさんに嘘つかれたりしながら試行錯誤したけど単純に以下な実装で問題なし
あとタブからのページ遷移のアニメーションが早すぎなので調整してみました

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PagerScreen(modifier: Modifier = Modifier) {
    val coroutineScope = rememberCoroutineScope()
    var tabIndex by remember { mutableStateOf(0) }
    val category = remember { mutableStateListOf<String>() }
    var pagerState = rememberPagerState(pageCount = {
        if (category.size == 0) 1
        else category.size
    })

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.collect { page ->
            tabIndex = page
        }
    }

    Column(modifier) {
        ScrollableTabRow(selectedTabIndex = tabIndex) {
            category.forEachIndexed { index, title ->
                LeadingIconTab(
                    selected = tabIndex == index,
                    onClick = {
                        tabIndex = index
                        coroutineScope.launch {
                            //pagerState.scrollToPage(index)
                            pagerState.animateScrollToPage(index, animationSpec = tween(400))
                        }
                    },
                    text = {
                        val max = LocalConfiguration.current.screenWidthDp.dp * (1F / 3F)
                        Text(title, overflow = TextOverflow.Ellipsis, maxLines = 1, modifier = Modifier.widthIn(max = max))
                    },
                    icon = {}
                )
            }
            // 固定Tab
            LeadingIconTab(
                selected = false,
                onClick = {
                    category.add("ページ ${category.size + 1}")
                },
                text = { Text("+ タブ追加") },
                icon = {}
            )
        }

        HorizontalPager(
            state = pagerState,
        ) { page ->
            if (category.size == 0) {
                Text("まだ何も登録されていません", modifier = Modifier.fillMaxSize())
            }
            else {
                Text("${category[page]}", modifier = Modifier.fillMaxSize())
            }
        }
    }
}

Android Studio Giraffe 2022.3.1 built on June 29, 2023