listOf get index numbers

I am following this tutorial here.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        val people = listOf("John", "Jack", "DJ", "Luke", "Matt", "Andrew", "Dave", "Steven", "Billy", "Zane", "Bobby", "Ryan", "Martin", "Werner", "Peter")

        setContent {
            RSSReaderTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding)
                    )

                    LazyColumn {
                        items(people) {
                            ListItem(it)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    RSSReaderTheme {
        Greeting("Android")
    }
}

@Composable
fun ListItem(name: String) {    
    Card(modifier = Modifier.fillMaxSize().padding(12.dp)) {
        Text(text = name, modifier = Modifier.padding(24.dp))
    }
}

What I want to do is the following:

Inside the ListItem function I want to also display (print) the index number of the “people” list.

For an example:

0 John

1 Jack

2 DJ

As I understand lists (arrays), the index of “John” will be 0, the index of “Andrew” will be 5, the index of “Ryan” will be 11.

@Composable
fun ListItem(name: String) {
    //print the index number of "name" on the l/h side of "Text"
    Card(modifier = Modifier.fillMaxSize().padding(12.dp)) {
        Text(text = name, modifier = Modifier.padding(24.dp))
    }
}

You mean something like this?

items(people.withIndex()) { (index, value) ->
    ListItem("$index $value")
}
2 Likes

A quick search reveals the itemsIndexed function:

LazyColumn {
    itemsIndexed(people) { index, item ->
        ListItem("$index: $item")
    }
}
3 Likes