0
0
Android Kotlinmobile~5 mins

Pagination basics in Android Kotlin

Choose your learning style9 modes available
Introduction

Pagination helps load data in small parts instead of all at once. This makes apps faster and saves memory.

Showing a long list of items like messages or products.
Loading search results page by page.
Displaying social media feeds that keep updating.
Fetching data from a server without freezing the app.
Syntax
Android Kotlin
fun loadPage(pageNumber: Int, pageSize: Int) {
    // Fetch data for the given page
}
pageNumber starts from 1 and increases for each new page.
pageSize is how many items you want to load per page.
Examples
Load the first page with 20 items.
Android Kotlin
loadPage(1, 20)
Load the second page with 10 items.
Android Kotlin
loadPage(2, 10)
Sample App

This app shows a list of items 5 at a time. When you tap "Load More", it shows the next 5 items.

Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            PaginationExample()
        }
    }
}

@Composable
fun PaginationExample() {
    var page by remember { mutableStateOf(1) }
    val pageSize = 5
    val allItems = (1..50).map { "Item $it" }
    val items = allItems.drop((page - 1) * pageSize).take(pageSize)

    Column {
        LazyColumn {
            items(items) { item ->
                Text(text = item)
            }
        }
        Button(onClick = { if (page * pageSize < allItems.size) page++ }) {
            Text(text = "Load More")
        }
    }
}
OutputSuccess
Important Notes

Always check if more pages exist before loading to avoid errors.

Use lazy loading lists like LazyColumn for better performance.

Keep UI responsive by loading pages asynchronously if fetching from a server.

Summary

Pagination splits data into small pages to improve app speed and memory use.

Use page number and page size to control which data to load.

Update the UI to show new pages when users request more data.