Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

List of Composables /Unit


I have a list of Composables i want to display in an HorizontalPager,these composables functions are composable components (e.g Button, InputTextfield, Box, Column etc).

@Composable
fun FirstScreen(){
 returns Column()
}

@Composable
fun SecondScreen(){
 returns Box()
}

val screens = ArrayList<Unit>()
        screens.add(FirstScreen())
        screens.add(SecondScreen())

val pagerState = rememberPagerState(
        pageCount = items.size,
        initialOffscreenLimit = 2,
        infiniteLoop = false,
        initialPage = 0,
    )

I place my HorizontalPager in a Scaffold and load the composable unit to display

  Scaffold(
            floatingActionButton = floatingActionButton,
            topBar = {
                TopAppBar(
                    title = title,
                    backgroundColor = topAppBarBackgroundColor,
                    showBackIcon,
                    onBackPressed
                )
            },
            content = { 
              HorizontalPager(state = pagerState, count = items.size,modifier = 
                 Modifier.fillMaxSize()) { page ->
                    items[page]
             }
              }
        )

Im able to see the composable function screen displayed in the horizontal pager, but the actions on the screens are disabled or not responding, ie i cant onClick a button or even gain focus for an input fields.Kindly advice what i've missed.


Solution

  • @Composable
    fun FirstScreen(){
       Column()
    }
    
    @Composable
    fun SecondScreen(){
       Box()
    }
    
    
    @Composable
    fun PagerScreen(){
    
    val pagerState = rememberPagerState()
    
    Scaffold(
            floatingActionButton = floatingActionButton,
            topBar = {
                TopAppBar(
                    title = title,
                    backgroundColor = topAppBarBackgroundColor,
                    showBackIcon,
                    onBackPressed
                )
            },
            content = {
                HorizontalPager(state = pagerState, count = items.size,modifier =
                Modifier.fillMaxSize()) { page ->
                    when(page){
                        0-> FirstScreen()
                        1-> SecondScreen()
                    }
                }
            }
        )}
    

    Please try this. Hope it will help