Popular Searches
Popular Course Categories
Popular Courses

Creating Composable Functions and Reusable Components

Creating Composable Functions and Reusable Components

Modern Android UI with Jetpack Compose

Creating Composable Functions and Reusable Components in Android

Course: Android App Development

Topic: Creating Composable Functions and Reusable Components

Course Link: Android App Development Course

Demo Registration: Register for a Course Demo

Website: JustAcademy Homepage


1. Introduction to Composable Functions

Jetpack Compose is a modern Android UI toolkit that allows developers to build user interfaces using Kotlin instead of defining every screen through traditional XML layouts. It follows a declarative approach, where developers describe what the interface should display based on the current application data and state.

Composable functions are the fundamental building blocks of Jetpack Compose. They allow developers to create individual UI elements, complete screens, and reusable components that can be combined to build complex applications.

For example, a login screen can be divided into reusable components such as a logo, heading, email field, password field, and login button. Each component can be created as a separate composable function and reused wherever required.

Learning Objectives

  • Understand Jetpack Compose and declarative UI development.
  • Learn the purpose and syntax of the @Composable annotation.
  • Create custom composable functions using Kotlin.
  • Pass parameters to reusable UI components.
  • Organize components using Row, Column, and Box.
  • Use Modifier to customize layout, appearance, and interaction.
  • Understand state management and recomposition.
  • Build a reusable form and profile card.
  • Apply best practices for maintainable Android applications.

2. What Is Jetpack Compose?

Jetpack Compose is Android's declarative UI toolkit for developing native interfaces. It provides composable functions, layout primitives, state management APIs, and Material Design components.

Important Features

  • Kotlin-based UI: Build interfaces directly in Kotlin.
  • Declarative programming: Describe the desired UI instead of manually updating every view.
  • Reusable components: Create functions that can be used in multiple screens.
  • State-driven interfaces: UI can update when observed state changes.
  • Composable layouts: Combine smaller functions to build larger screens.
  • Material Design support: Use ready-made components such as Button, Card, TextField, and Scaffold.

Traditional XML Layouts vs. Jetpack Compose

Feature Traditional Android UI Jetpack Compose
UI definition Usually XML layouts Kotlin functions
UI building blocks Views and ViewGroups Composable functions
Updating UI Often requires explicit view updates State changes can trigger recomposition
Reusable UI Custom views, XML includes, and adapters Reusable composable functions
Layout structure XML hierarchy or programmatic views Composable functions and layout primitives
Styling XML attributes and resources Modifiers, parameters, and themes

3. Understanding the @Composable Annotation

The @Composable annotation identifies a Kotlin function that participates in the Compose composition process. It allows the function to call other composable functions and describe UI content.

Basic Syntax

import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

@Composable
fun WelcomeMessage() {
    Text(text = "Welcome to Android Development")
}

Explanation:

  • import androidx.compose.runtime.Composable imports the annotation.
  • @Composable marks the function as a composable function.
  • fun WelcomeMessage() declares a custom Kotlin function.
  • Text() displays text on the screen.

Unlike a regular Kotlin function that returns a value, a typical UI composable emits UI content and returns Unit. Composable functions are designed to be called from a compatible Compose context.

4. Creating Your First Composable Function

To create a composable function, define a Kotlin function, add the @Composable annotation, and use existing Compose components inside it.

Example: Welcome Screen

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun WelcomeScreen() {
    Column(
        modifier = Modifier.padding(16.dp)
    ) {
        Text(text = "Welcome!")
        Text(text = "Learn Android development with Kotlin.")
    }
}

This function creates a vertical layout containing two text elements. The padding modifier adds space around the content.

Displaying the Composable in an Activity

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface

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

        setContent {
            MaterialTheme {
                Surface {
                    WelcomeScreen()
                }
            }
        }
    }
}

The setContent block establishes the Compose UI for the activity. The WelcomeScreen() function is called inside that block to display the screen.

Note: This example assumes that the project has the required Jetpack Compose, Activity Compose, and Material 3 dependencies configured.

5. Naming Conventions for Composable Functions

Readable naming conventions help developers understand what a component represents and how it should be used. Composable functions that emit UI are generally named using PascalCase and descriptive nouns.

Function Name Purpose
ProfileCard() Displays profile information.
LoginForm() Displays login fields and actions.
ProductItem() Displays a product summary.
SectionHeader() Displays a section heading.
PrimaryButton() Displays a reusable primary action.

Prefer descriptive names that communicate the component's role instead of vague names such as UI1() or MyFunction().

6. Passing Parameters to Composable Functions

Parameters allow a composable function to display different content without duplicating its implementation. For example, one greeting component can display a welcome message for different users.

Example: Greeting Component

import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

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

Using the Component

@Composable
fun GreetingScreen() {
    Greeting(name = "Aarav")
    Greeting(name = "Priya")
    Greeting(name = "Rahul")
}

The same composable is reused three times with different parameter values.

Benefits of Parameters

  • Reduce repeated code.
  • Make components flexible and configurable.
  • Improve testability.
  • Make UI components easier to maintain.
  • Allow data to flow from parent components to child components.

7. Using Default Parameters

Kotlin supports default parameter values. They allow a component to provide standard behavior while still allowing callers to customize it.

Example

@Composable
fun Greeting(
    name: String = "Guest"
) {
    Text(text = "Welcome, $name!")
}

Usage

@Composable
fun HomeScreen() {
    Greeting()
    Greeting(name = "Ananya")
}

The first call uses the default name, while the second supplies a custom name.

8. Understanding Modifier in Jetpack Compose

Modifier is an important Compose API used to customize a component's layout, size, padding, background, click behavior, and other properties.

Exposing a modifier: Modifier = Modifier parameter in reusable components allows callers to control how those components fit into different layouts.

Example: Modifier with Text

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun HighlightedText(
    text: String,
    modifier: Modifier = Modifier
) {
    Text(
        text = text,
        modifier = modifier
            .background(Color.LightGray)
            .padding(12.dp)
    )
}

Using the Modifier Parameter

@Composable
fun ExampleScreen() {
    HighlightedText(
        text = "Reusable Component",
        modifier = Modifier.padding(16.dp)
    )
}

The caller can add outer spacing without changing the implementation of the reusable component.

Common Modifier Functions

Modifier Purpose
padding() Adds space around the content or within the modifier chain.
fillMaxWidth() Requests the maximum available width.
fillMaxSize() Requests the maximum available width and height.
width() Specifies a preferred width.
height() Specifies a preferred height.
background() Draws a background behind content.
clickable() Makes a component respond to click interactions.
border() Adds a border to a component.
clip() Clips content to a specified shape.

9. Organizing Components with Row, Column, and Box

Compose provides layout composables for arranging content. Choosing the correct layout makes reusable components easier to understand and maintain.

Column

Column arranges its children vertically.

@Composable
fun UserDetails() {
    Column {
        Text(text = "Name: Riya")
        Text(text = "Role: Android Developer")
        Text(text = "Experience: 2 years")
    }
}

Row

Row arranges its children horizontally.

import androidx.compose.foundation.layout.Row

@Composable
fun UserSummary() {
    Row {
        Text(text = "Riya")
        Text(text = " - Android Developer")
    }
}

Box

Box allows children to be placed within the same area, which is useful for overlays and layered layouts.

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Alignment

@Composable
fun ImagePlaceholder() {
    Box(
        modifier = Modifier.size(120.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "Profile Image")
    }
}

10. Creating Reusable Components

A reusable component is a UI element designed to be used in multiple places. Instead of repeating the same code across different screens, developers create a dedicated composable and configure it through parameters.

Example: Reusable Section Header

@Composable
fun SectionHeader(
    title: String,
    subtitle: String? = null,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.padding(vertical = 8.dp)
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleLarge
        )

        if (subtitle != null) {
            Text(
                text = subtitle,
                style = MaterialTheme.typography.bodyMedium
            )
        }
    }
}

Using the Section Header

@Composable
fun DashboardScreen() {
    Column(modifier = Modifier.padding(16.dp)) {
        SectionHeader(
            title = "My Courses",
            subtitle = "Continue learning"
        )

        SectionHeader(
            title = "Assignments",
            subtitle = "Review your pending tasks"
        )
    }
}

The component keeps the heading and optional subtitle consistent across multiple sections.

11. Building a Reusable Profile Card

A profile card is a practical example of combining several smaller composables into one reusable component.

Complete Example

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun ProfileCard(
    name: String,
    role: String,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 4.dp
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = name,
                style = MaterialTheme.typography.titleLarge
            )

            Text(
                text = role,
                style = MaterialTheme.typography.bodyMedium
            )
        }
    }
}

Displaying Multiple Profile Cards

@Composable
fun TeamScreen() {
    Column(
        modifier = Modifier.padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        ProfileCard(
            name = "Riya Sharma",
            role = "Android Developer"
        )

        ProfileCard(
            name = "Aman Verma",
            role = "UI Designer"
        )

        ProfileCard(
            name = "Neha Patel",
            role = "Project Manager"
        )
    }
}

This example demonstrates how one component can display different data while maintaining the same design.

12. Creating Reusable Buttons

Buttons are frequently reused throughout an application. A reusable button component can standardize text, spacing, enabled state, and click behavior.

Example: Primary Action Button

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

@Composable
fun PrimaryActionButton(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true
) {
    Button(
        onClick = onClick,
        modifier = modifier,
        enabled = enabled
    ) {
        Text(text = text)
    }
}

Using the Button

@Composable
fun ActionScreen() {
    Column(modifier = Modifier.padding(16.dp)) {
        PrimaryActionButton(
            text = "Save",
            onClick = { /* Save data */ },
            modifier = Modifier.fillMaxWidth()
        )

        PrimaryActionButton(
            text = "Continue",
            onClick = { /* Navigate or continue */ },
            modifier = Modifier.fillMaxWidth()
        )
    }
}

The callback allows the parent screen to decide what happens when the button is clicked. The reusable component does not need to know the business logic of every screen.

13. Creating Reusable Input Fields

Text fields are another common component that benefits from reuse. A shared input component can standardize labels, placeholder text, and layout behavior.

Example: Reusable Text Input

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

@Composable
fun AppTextField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String,
    modifier: Modifier = Modifier,
    enabled: Boolean = true
) {
    OutlinedTextField(
        value = value,
        onValueChange = onValueChange,
        label = { Text(label) },
        modifier = modifier.fillMaxWidth(),
        enabled = enabled,
        singleLine = true
    )
}

This component receives the current value and a callback to report changes. The parent owns the value, so the input can be reused in forms that have different state-management requirements.

14. Understanding State in Composable Functions

State represents data that can change over time and affect the UI. Examples include whether a password is visible, the current text in a field, the number of items in a cart, and whether a user has selected an option.

When Compose observes a state change, it can schedule recomposition for the composables that read that state. Recomposition re-executes the relevant composable code to update the UI.

Example: Counter Component

import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

@Composable
fun Counter() {
    var count by remember {
        mutableIntStateOf(0)
    }

    Button(
        onClick = { count++ }
    ) {
        Text(text = "Count: $count")
    }
}

Explanation:

  • mutableIntStateOf(0) creates observable integer state initialized to zero.
  • remember retains the state across recompositions while the composable remains in the same composition location.
  • by delegates property access to the state object.
  • Clicking the button increments the counter.
  • Compose updates the displayed count when the state changes.

For state that must survive activity recreation, use an appropriate state-saving approach such as rememberSaveable. For longer-lived application state, consider a ViewModel or another suitable state holder.

15. Stateless and Stateful Components

Composable components can be designed as stateful or stateless. Understanding the difference helps developers build predictable and reusable UI.

Feature Stateful Component Stateless Component
State ownership Manages some state internally Receives state from its caller
Configuration May provide behavior without requiring all state externally Uses explicit parameters and callbacks
Reuse Useful when encapsulated state is part of the component's purpose Often easier to reuse in different contexts
Example A counter that owns its count A counter display that receives count and an increment callback

Example: Stateless Counter

@Composable
fun CounterDisplay(
    count: Int,
    onIncrement: () -> Unit
) {
    Button(onClick = onIncrement) {
        Text(text = "Count: $count")
    }
}

The component does not store the counter value. Its caller supplies the current count and defines how that value changes.

16. Reusable Components and State Hoisting

State hoisting means moving state ownership to a common parent so that child components can receive the state and communicate changes through callbacks.

Example: Hoisted Counter State

@Composable
fun CounterScreen() {
    var count by remember {
        mutableIntStateOf(0)
    }

    CounterDisplay(
        count = count,
        onIncrement = { count++ }
    )
}

In this design, CounterScreen owns the counter state, while CounterDisplay renders the value and reports user actions. This pattern improves testability and makes it easier to coordinate state across multiple components.

17. Creating a Reusable Login Form

A login form demonstrates how several reusable composables can be assembled into a complete screen. The example below includes state for the email and password fields and a reusable action button.

Complete Example

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun LoginForm(
    onLogin: (String, String) -> Unit,
    modifier: Modifier = Modifier
) {
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }

    Column(
        modifier = modifier.padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Text(
            text = "Login",
            style = MaterialTheme.typography.headlineMedium
        )

        AppTextField(
            value = email,
            onValueChange = { email = it },
            label = "Email"
        )

        AppTextField(
            value = password,
            onValueChange = { password = it },
            label = "Password"
        )

        PrimaryActionButton(
            text = "Sign In",
            onClick = {
                onLogin(email, password)
            },
            modifier = Modifier.fillMaxWidth(),
            enabled = email.isNotBlank() &&
                password.isNotBlank()
        )
    }
}

Using the Login Form

@Composable
fun LoginScreen() {
    LoginForm(
        onLogin = { email, password ->
            // Connect to authentication logic here.
            // Never log or expose a user's password.
        }
    )
}

This is a UI demonstration, not a complete authentication system. A real application should validate input appropriately, use a secure authentication service, handle errors, and never store passwords in plain text.

18. Creating a List of Reusable Components

Reusable components are particularly useful when displaying repeated data such as products, courses, contacts, or messages. Compose provides LazyColumn for efficiently displaying vertically scrolling lists.

Example: Course Item

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

data class Course(
    val id: Int,
    val title: String,
    val description: String
)

@Composable
fun CourseItem(
    course: Course,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(text = course.title)
            Text(text = course.description)
        }
    }
}

Displaying Courses with LazyColumn

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.unit.dp

@Composable
fun CourseList(courses: List<Course>) {
    LazyColumn(
        modifier = Modifier.padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        items(
            items = courses,
            key = { course -> course.id }
        ) { course ->
            CourseItem(course = course)
        }
    }
}

The unique key helps Compose identify each course item when the list changes. This is especially useful when items move, are inserted, or are removed.

19. Composable Function Recomposition

Recomposition occurs when Compose re-executes composable functions to reflect changes in the state they read or in the inputs that affect their output.

How Recomposition Works

  1. Compose executes a composable for the initial UI composition.
  2. The composable reads state and describes the UI.
  3. An observed state value changes.
  4. Compose schedules recomposition for affected parts of the UI.
  5. The updated composable output is applied to the existing composition.

Developers should write composable functions so that executing them again with the same inputs is safe. Avoid performing network requests, database writes, or other uncontrolled side effects directly in the body of a composable. Use appropriate effect APIs or architecture layers for side effects.

20. Organizing Composable Functions into Files

As an application grows, keeping every component in one Kotlin file becomes difficult. Organizing related composables into separate files improves readability and maintainability.

Example Project Structure

com.example.myapp
|
|-- MainActivity.kt
|-- ui
|   |-- screens
|   |   |-- HomeScreen.kt
|   |   |-- LoginScreen.kt
|   |   |-- ProfileScreen.kt
|   |
|   |-- components
|   |   |-- PrimaryActionButton.kt
|   |   |-- AppTextField.kt
|   |   |-- ProfileCard.kt
|   |   |-- SectionHeader.kt
|   |
|   |-- theme
|       |-- Color.kt
|       |-- Theme.kt
|       |-- Type.kt
|
|-- data
|   |-- Course.kt
|   |-- User.kt
|
|-- viewmodel
    |-- LoginViewModel.kt

This structure is an example rather than a mandatory convention. Choose file and package boundaries based on the size and architecture of the project.

21. Common Mistakes When Creating Composables

Mistake Why It Is a Problem Recommended Solution
Repeating identical UI code Changes must be made in multiple places Extract a reusable composable.
Using unclear names Components become difficult to understand Use descriptive PascalCase names.
Hard-coding every value Components become less flexible Expose important values as parameters.
Not exposing a Modifier parameter Callers have less control over layout placement Use a default modifier parameter where appropriate.
Putting unrelated responsibilities into one component The component becomes difficult to test and maintain Split it into focused building blocks.
Mutating ordinary variables as UI state Changes may not trigger recomposition Use observable Compose state or an appropriate state holder.
Performing network calls directly during composition Recomposition may repeat unintended operations Use a ViewModel and suitable effect or data-loading APIs.
Keeping all state inside deeply nested components Other components cannot easily coordinate shared data Hoist shared state to an appropriate owner.
Ignoring accessibility Components may be difficult to use with assistive technologies Use suitable semantics, labels, and accessible interaction patterns.

22. Best Practices for Reusable Components

  • Give each component one clear responsibility.
  • Use descriptive names that explain the component's purpose.
  • Pass changing data through parameters rather than duplicating components.
  • Expose event callbacks such as onClick instead of embedding screen-specific business logic.
  • Provide a Modifier parameter when callers should customize layout or appearance.
  • Prefer stateless components when external state ownership improves flexibility.
  • Use state hoisting to coordinate state between related components.
  • Use existing Material 3 components when they already satisfy the design requirements.
  • Keep side effects out of ordinary composable execution.
  • Use stable identifiers for items in dynamic lists where appropriate.
  • Make components accessible and test them with different screen sizes and font settings.
  • Extract a reusable component when it meaningfully reduces duplication or clarifies the UI structure.

23. Practical Exercises

Exercise 1: Greeting Component

Create a composable function named GreetingCard that accepts a person's name and displays a personalized greeting.

Exercise 2: Reusable Button

Create a primary button component that accepts button text, an enabled flag, a Modifier, and an onClick callback.

Exercise 3: Profile Card

Build a profile card that displays a user's name, role, and a short description. Reuse the component for at least three different users.

Exercise 4: Registration Form

Build a form using reusable text fields and a submit button. Hoist the form state to an appropriate parent composable and validate required inputs.

Exercise 5: Course List

Create a data class for a course, a reusable CourseItem component, and a LazyColumn that displays multiple courses with unique keys.

Exercise 6: State Management

Create a counter component in both stateful and stateless versions. Compare how each approach affects reuse and testing.

24. Interview Questions and Answers

Q1. What is a composable function?

A composable function is a Kotlin function marked with @Composable that participates in the Compose UI composition process and can describe UI content.

Q2. What is Jetpack Compose?

Jetpack Compose is Android's declarative UI toolkit for building native interfaces using Kotlin.

Q3. Why do we use the @Composable annotation?

It identifies a function that can participate in composition and call other composable functions.

Q4. What is a reusable component?

A reusable component is a UI building block that can be used in multiple places, usually with different input values or callbacks.

Q5. What is Modifier in Compose?

Modifier provides a way to customize layout, appearance, and interaction behavior for composable elements.

Q6. What is the difference between Row and Column?

Row arranges children horizontally, while Column arranges children vertically.

Q7. What is recomposition?

Recomposition is the process through which Compose re-executes affected composables to reflect changes in observed state or relevant inputs.

Q8. What is state hoisting?

State hoisting moves state ownership to a caller or parent component and passes the value and callbacks to child components.

Q9. What is the difference between stateful and stateless composables?

A stateful composable owns some state internally, whereas a stateless composable receives the state it needs through parameters and communicates changes through callbacks.

Q10. Why should reusable components accept callbacks?

Callbacks allow the caller to define the behavior of interactions without coupling the component to a specific screen or business operation.

Q11. Why should a composable accept a Modifier parameter?

A Modifier parameter lets callers customize the component's placement, sizing, padding, and other supported behavior without modifying its implementation.

Q12. How can repeated list items be displayed efficiently?

Use LazyColumn or another appropriate lazy layout and provide stable, unique keys when the data has reliable identifiers.

25. Quick Revision Checklist

  • Jetpack Compose builds Android UI with Kotlin.
  • The @Composable annotation marks composable functions.
  • Composable functions can call other composables.
  • Parameters allow components to display different data.
  • Default parameters provide convenient fallback values.
  • Modifier customizes layout and component behavior.
  • Row, Column, and Box organize UI elements.
  • Reusable components reduce duplication.
  • State changes can trigger recomposition.
  • State hoisting separates state ownership from UI presentation.
  • Callbacks allow parent components to define interaction behavior.
  • LazyColumn is useful for displaying large or scrollable lists.
  • Focused components are easier to test and maintain.

26. Conclusion

Creating composable functions and reusable components is a core skill in modern Android development with Jetpack Compose. Composable functions make it possible to describe UI declaratively, while reusable components help maintain consistency and reduce repeated code. By using parameters, Modifier, layout composables, state management, and state hoisting effectively, developers can build Android applications that are modular, scalable, testable, and easier to maintain.

Explore Android development training and course registration through the following links:

Previous Next
whatsapp