How to Show Simple List in Android Jetpack Compose

By Mohammed Rashid •  November 11th, 2022 • 

Most mobile apps have a feature or screen that shows some sort of lists. In this Jetpack compose tutorial, let’s learn how to create and display a simple list of texts in Android.

LazyColumn and LazyRow are two composables that are used to show long lists. They are efficient because they render only the element visible on the screen. Here, I am using LazyColumn to display a list of strings.

@Composable
fun TextList() {
    val listA = listOf<String>("Example", "Android", "Tutorial", "Jetpack", "Compose", "List", "Example","Simple")
    LazyColumn(
        modifier = Modifier.fillMaxWidth(),
        contentPadding = PaddingValues(16.dp)
    ) {
        items(listA) { item ->
                Spacer(modifier = Modifier.height(200.dp))
                Text(text = item)
        }
    }
}

As you see, I created a string list and then passed it to items. Text composable and Spacer composable are rendered for each item in the declared list. The complete code is given below.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    TextList()
                }
            }
        }
    }
}

@Composable
fun TextList() {
    val listA = listOf<String>("Example", "Android", "Tutorial", "Jetpack", "Compose", "List", "Example","Simple")
    LazyColumn(
        modifier = Modifier.fillMaxWidth(),
        contentPadding = PaddingValues(16.dp)
    ) {
        items(listA) { item ->
                Spacer(modifier = Modifier.height(200.dp))
                Text(text = item)
        }
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        TextList()
    }
}

See the output of this Android Jetpack Compose list example.

I hope this simple tutorial to show lists in Android Jetpack Compose will be helpful for you.

Mohammed Rashid

Keep Reading