Jetpack Compose : Tab Layout + View Pager

aram·2021년 10월 30일
0

Implement Library

implementation "com.google.accompanist:accompanist-pager:0.12.0"

Tab Layout + View Pager

@OptIn(ExperimentalPagerApi::class)
@Composable
fun Procedures(slug: String){
    val tabData = listOf(
        Procedure.treatment.value,
        Procedure.diagnostic.value
    )
    val pagerState = rememberPagerState(
        pageCount = tabData.size,
        initialOffscreenLimit = 2,
        infiniteLoop = true,
        initialPage = 0,
    )
    val tabIndex = pagerState.currentPage
    val coroutineScope = rememberCoroutineScope()
    
    // TAB
    TabRow(selectedTabIndex = tabIndex,
        modifier = Modifier.padding(top = 20.dp)) {
        tabData.forEachIndexed { index, text ->
            Tab(selected = tabIndex == index, onClick = {
                coroutineScope.launch {
                    pagerState.animateScrollToPage(index)
                }
            }, text = {
                Text(text = text)
            })
        }
    }

    // PAGER
    HorizontalPager(
        state = pagerState
    ) { index ->
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            if (tabData[index] == Procedure.treatment.value) {
                Services(Procedure.treatment, slug)
            } else {
                Services(Procedure.diagnostic, slug)
            }
        }
    }
}
@Composable
fun Services(procedure: Procedure, slug: String) {
    val viewModel: ProcedureVM = viewModel()
    val services = viewModel.services.observeAsState().value
    val loadingState = viewModel.loading.observeAsState().value

    LaunchedEffect("GET_HOSPITALS_SERVICES") {
        viewModel.fetchHospitalService(procedure, slug, 20)
    }

    if (loadingState == true) {
        LoadingBar()
    } else {
        services?.items?.let { services ->
            Column(Modifier.fillMaxWidth()) {
                services.forEach { service ->
                    Row(horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.fillMaxWidth().padding(vertical = 5.dp)
                    ) {
                        Text(text = service.name!!, modifier = Modifier.width(200.dp), maxLines = 2)
                        Text(text = price(service), color = MaterialTheme.colors.primaryVariant)
                    }
                }
            }
        }
    }
}

SpaceBetween
잠깐 팁.
Row()에서 horizontalArrangement 를 적용하기 위해서는 부모의 width 값이 fillMaxWidth() 여야 한다.

참고
https://levelup.gitconnected.com/implement-tablayout-with-viewpager-in-android-jetpack-compose-d509fc6e2d8e

0개의 댓글