androidkotlinandroid-jetpack-composelazy-loadinglazycolumn

Display different composable item in Multi type Lazy Column after every 5th Item in Jetpack Compose


I have two lists, number list of length 200 and and alphabet list of length 26. Both lists have different composable items to show them i.e NumberItem() and AlphabetItem().

I want AlphabetItem() to be displayed after every 5 items of NumberItem() in LazyColoumn.

My code and results:

    @Composable
fun LazyColumnWithMultipleTypesSample() {
    val numList = (1..200).toList()
    val alphabetList = ('A'..'Z').toList()
    val context = LocalContext.current

    LazyColumn(modifier = Modifier.fillMaxSize()) {
        items(count = numList.size + alphabetList.size) { index ->



            if (index % 5 == 0 && index / 5 < alphabetList.size) { //for index=0 , index%5==0 is always true, hence we make sure index is not 0 so this item does not appear as first item
                // Display alphabet item
                AlphabetItem(
                    char = alphabetList[index / 5], //-1 so 0th index also be seen
                    onClick = { char ->
                        Toast.makeText(context, "Alphabet clicked: $char", Toast.LENGTH_SHORT)
                            .show()
                    }
                )
            }
            // Display number item
            val numIndex = index
            if (numIndex < numList.size) //checking index overflow is not there
                NumberItem(
                    number = numList[numIndex],
                    onClick = { number ->
                        Toast.makeText(context, "Number clicked: $number", Toast.LENGTH_SHORT)
                            .show()
                    }
                )

        }
    }
}

Screenshot of App running

Notice, the first AlphabetItem() is not in the 6th index but at the 0th index.

I want 5 items of NumberItem() then 1 AlphabetItem() and so on. If AlphabetList get exhausted show only numberItem after that.

I have tried, extra if(index>0) check for AlphabetItem() which loaded all items except for alphabet "A".


Solution

  • You can decrease index / 5 by 1 when calculating the index of alphabetList, so index 0 becomes -1, 5 becomes 0 and so on.

    if (index % 5 == 0 && (index / 5 - 1) in 0..alphabetList.lastIndex) {
        AlphabetItem(
            char = alphabetList[index / 5 - 1],
    

    Alteratively, create a range of acceptable indices and check against it.

    val alphabetRange = 1..alphabetList.size
    ...
    if (index % 5 == 0 && index / 5 in alphabetRange) {
        AlphabetItem(
            char = alphabetList[index / 5 - 1],