Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modern Android 13 Development Cookbook

You're reading from   Modern Android 13 Development Cookbook Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Arrow left icon
Product type Paperback
Published in Jul 2023
Publisher Packt
ISBN-13 9781803235578
Length 322 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Madona S. Wambua Madona S. Wambua
Author Profile Icon Madona S. Wambua
Madona S. Wambua
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Getting Started with Modern Android Development Skills 2. Chapter 2: Creating Screens Using a Declarative UI and Exploring Compose Principles FREE CHAPTER 3. Chapter 3: Handling the UI State in Jetpack Compose and Using Hilt 4. Chapter 4: Navigation in Modern Android Development 5. Chapter 5: Using DataStore to Store Data and Testing 6. Chapter 6: Using the Room Database and Testing 7. Chapter 7: Getting Started with WorkManager 8. Chapter 8: Getting Started with Paging 9. Chapter 9: Building for Large Screens 10. Chapter 10: Implementing Your First Wear OS Using Jetpack Compose 11. Chapter 11: GUI Alerts – What’s New in Menus, Dialog, Toast, Snackbars, and More in Modern Android Development 12. Chapter 12: Android Studio Tips and Tricks to Help You during Development 13. Index 14. Other Books You May Enjoy

Implementing a scrollable list in Jetpack Compose

When building Android applications, one thing that we can all agree on is you must know how to build a RecyclerView to display your data. With our new, modern way of building Android applications, if we need to use RecyclerView, we can use LazyColumn, which is similar. In this recipe, we will look at rows, columns, and LazyColumn, and build a scrollable list using our dummy data.

In addition, we will be learning some Kotlin in the process.

Getting ready

We will continue using the Compose Basics project to build a scrollable list; hence, to get started, you need to have done the previous recipe.

How to do it…

Follow these steps to build your first scrollable list:

  1. Let us go ahead and build our first scrollable list, but first, we need to create our dummy data, and this is the item we want to be displayed on our list. Hence, create a package called favoritecity where our scrollable example will live.
  2. Inside the favoritecity package, create a new data class and call it City; this will be our dummy data source – data class City ().
  3. Let us model our City data class. Make sure you add the necessary imports once you have added the annotated values:
    data class City(
        val id: Int,
        @StringRes val nameResourceId: Int,
        @DrawableRes val imageResourceId: Int
    )
  4. Now, in our dummy data, we need to create a Kotlin class and call this class CityDataSource. In this class, we will create a function called loadCities(), which will return our list of List<City>, which we will display in our scrollable list. Check the Technical requirements section for all the required imports to get all the code and images:
    class CityDataSource {
        fun loadCities(): List<City> {
            return listOf<City>(
                City(1, R.string.spain, R.drawable.spain),
                City(2, R.string.new_york,
                    R.drawable.newyork),
                City(3, R.string.tokyo, R.drawable.tokyo),
                City(4, R.string.switzerland,
                    R.drawable.switzerland),
                City(5, R.string.singapore,
                    R.drawable.singapore),
                City(6, R.string.paris, R.drawable.paris),
            )
        }
    }
  5. Now, we have our dummy data, and it is time to display this on our scrollable list. Let’s create a new Kotlin file in our components package and call it CityComponents. In CityComponents, we will create our @Preview function:
    @Preview(showBackground = true)
    @Composable
    private fun CityCardPreview() {
        CityApp()
    }
  6. Inside our @Preview function, we have another composable function, CityApp(); inside this function, we will call our CityList composable function, which has the list as a parameter. In addition, in this composable function, we will call LazyColumn, and items will be CityCard(cities). See the How it works section for further explanation about LazyColumn and items:
    @Composable
    fun CityList(cityList: List<City>) {
        LazyColumn {
            items(cityList) { cities ->
                CityCard(cities)
            }
        }
    }
  7. Finally, let us construct our CityCard(city) composable function:
    @Composable
    fun CityCard(city: City) {
        Card(modifier = Modifier.padding(10.dp),
        elevation = 4.dp) {
            Column {
                Image(
                    painter = painterResource(
                        city.imageResourceId),
                    contentDescription = stringResource(
                        city.nameResourceId),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(154.dp),
                    contentScale = ContentScale.Crop
                )
                Text(
                    text = LocalContext.current.getString(
                        city.nameResourceId),
                    modifier = Modifier.padding(16.dp),
                    style = MaterialTheme.typography.h5
                )
            }
        }
    }
  8. When you run the CityCardPreview composable function, you should have a scrollable list, as seen in Figure 2.6.
Figure 2.7 – A scrollable list of cities

Figure 2.7 – A scrollable list of cities

How it works…

In Kotlin, a list has two types, immutable and mutable. Immutable lists are items that cannot be modified, whereas mutable lists are items in the list that can be modified. To define a list, we can say a list is a generic ordered collection of elements, and these elements can be in the form of integers, strings, images, and so on, which is mostly informed by the type of data we want our lists to contain. For instance, in our example, we have a string and image helping identify our favorite cities by name and image.

In our City data class, we use @StringRes, and @DrawableRes in order to just pull this directly from the res folders for Drawable and String easily, and they also represent the ID for the images and string.

We created CityList and annotated it with the composable function and declared the list of city objects as our parameter in the function. A scrollable list in Jetpack Compose is made using LazyColumn. The main difference between LazyColumn and Column is that when using Column, you can only display small items, as Compose loads all items at once.

In addition, a column can only hold fixed composable functions, whereas LazyColumn, as the name suggests, loads the content as required on demand, making it good for loading more items when needed. In addition, LazyColumn comes with a scrolling ability inbuilt, which makes work easier for developers.

We also created a composable function, CityCard, where we import the Card() element from Compose. A card contains content and actions about a single object; in our example, for instance, our card has an image and the name of the city. A Card() element in Compose has the following inputs in its parameter:

@Composable
fun Card(
    modifier: Modifier = Modifier,
    shape: Shape = MaterialTheme.shapes.medium,
    backgroundColor: Color = MaterialTheme.colors.surface,
    contentColor: Color = contentColorFor(backgroundColor),
    border: BorderStroke? = null,
    elevation: Dp = 1.dp,
    content: @Composable () -> Unit
),

This means you can easily model your card to the best fitting; our card has padding and elevation, and the scope has a column. In this column, we have an image and text, which helps describe the image for more context.

See also

There is more to learn about lists and grids in Compose; you can use this link to learn more: https://developer.android.com/jetpack/compose/lists.

You have been reading a chapter from
Modern Android 13 Development Cookbook
Published in: Jul 2023
Publisher: Packt
ISBN-13: 9781803235578
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime