🦁

Jetpack ComposeでスワイプできるTabを作る

2022/08/12に公開
@OptIn(ExperimentalPagerApi::class)
@Composable
fun TestTabs() {
    var tabIndex by remember { mutableStateOf(0) }
    val tabTitles = listOf("Hello", "There", "World")
    val pagerState = rememberPagerState() // 2.
    val scope = rememberCoroutineScope()

    Column {
        TabRow(selectedTabIndex = tabIndex,
            indicator = { tabPositions -> // 3.
                TabRowDefaults.Indicator(
                    Modifier.pagerTabIndicatorOffset(
                        pagerState,
                        tabPositions
                    )
                )
            }) {
            tabTitles.forEachIndexed { index, title ->
                Tab(selected = tabIndex == index,
                    onClick = {
                        scope.launch {
                            tabIndex = index
                            pagerState.animateScrollToPage(index)
                        }
                    },
                    text = { Text(text = title) })
            }
        }
        HorizontalPager(
            count = tabTitles.size,
            state = pagerState,
        ) { tabIndex ->
            Text(
                tabIndex.toString(),
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.White)
            )
        }
    }
}

Discussion