36,99 €
Unlock the full potential of Android app development with Jetpack Compose 1.7. This all-in-one guide equips you to build sophisticated, modern Android applications using cutting-edge tools like Android Studio, Material Design 3, and Kotlin. Perfect for developers aiming to go from setup to deployment, the book leads you through each phase of app creation—from mastering Android Studio basics to publishing on the Google Play Store.
Start with setting up your environment, then dive into Kotlin essentials, covering data types, functions, coroutines, and more to lay a solid programming foundation. Explore Jetpack Compose fundamentals and Android architecture as you work through practical tutorials on custom Composables, and layouts like rows, columns, boxes, flows, pagers, and lists. Beyond layout design, you’ll learn state management, navigation, modifiers, and custom components.
Gain advanced capabilities with features like biometric authentication, Google Maps integration, and in-app billing for monetization. Further, expand your skills with graphics, animations, and gesture handling to build dynamic and interactive interfaces. Master data storage using Room databases, ViewModels, and LiveData for a complete end-to-end app experience.
To help you track your progress, the book offers access to over 55 online quizzes covering each key concept, allowing you to test your knowledge as you go. Each lesson is supported by hands-on tutorials and downloadable source code, making it easy to follow along and practice.
For developers ready to bring their app ideas to life, this guide provides a complete roadmap, from development to publication. Elevate your Android development skills with this essential guide to Jetpack Compose 1.7.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 786
Veröffentlichungsjahr: 2024
Jetpack Compose 1.7
Essentials
Jetpack Compose 1.7 Essentials
ISBN-13: 978-1-965764-03-9
© 2024 Neil Smyth / Payload Media, Inc. All Rights Reserved.
This book is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights reserved.
The content of this book is provided for informational purposes only. Neither the publisher nor the author offers any warranties or representation, express or implied, with regard to the accuracy of information contained in this book, nor do they accept any liability for any loss or damage arising from any errors or omissions.
This book contains trademarked terms that are used solely for editorial purposes and to the benefit of the respective trademark owner. The terms used within this book are not intended as infringement of any trademarks.
Rev: 1.0
https://www.payloadbooks.com
Copyright
“
Table of Contents
1. Start Here
1.1 For Kotlin programmers
1.2 For new Kotlin programmers
1.3 Downloading the code samples
1.4 Feedback
1.5 Errata
1.6 Take the knowledge tests
2. Setting up an Android Studio Development Environment
2.1 System requirements
2.2 Downloading the Android Studio package
2.3 Installing Android Studio
2.3.1 Installation on Windows
2.3.2 Installation on macOS
2.3.3 Installation on Linux
2.4 The Android Studio setup wizard
2.5 Installing additional Android SDK packages
2.6 Installing the Android SDK Command-line Tools
2.6.1 Windows 8.1
2.6.2 Windows 10
2.6.3 Windows 11
2.6.4 Linux
2.6.5 macOS
2.7 Android Studio memory management
2.8 Updating Android Studio and the SDK
2.9 Summary
3. A Compose Project Overview
3.1 About the project
3.2 Creating the project
3.3 Creating an activity
3.4 Defining the project and SDK settings
3.5 Previewing the example project
3.6 Reviewing the main activity
3.7 Preview updates
3.8 Bill of Materials and the Compose version
3.9 Take the knowledge test
3.10 Summary
4. An Example Compose Project
4.1 Getting started
4.2 Removing the template Code
4.3 The Composable hierarchy
4.4 Adding the DemoText composable
4.5 Previewing the DemoText composable
4.6 Adding the DemoSlider composable
4.7 Adding the DemoScreen composable
4.8 Previewing the DemoScreen composable
4.9 Adjusting preview settings
4.10 Testing in interactive mode
4.11 Completing the project
4.12 Summary
5. Creating an Android Virtual Device (AVD) in Android Studio
5.1 About Android Virtual Devices
5.2 Starting the Emulator
5.3 Running the Application in the AVD
5.4 Real-time updates with Live Edit
5.5 Running on Multiple Devices
5.6 Stopping a Running Application
5.7 Supporting Dark Theme
5.8 Running the Emulator in a Separate Window
5.9 Removing the Device Frame
5.10 Take the knowledge test
5.11 Summary
6. Using and Configuring the Android Studio AVD Emulator
6.1 The Emulator Environment
6.2 Emulator Toolbar Options
6.3 Working in Zoom Mode
6.4 Resizing the Emulator Window
6.5 Extended Control Options
6.5.1 Location
6.5.2 Displays
6.5.3 Cellular
6.5.4 Battery
6.5.5 Camera
6.5.6 Phone
6.5.7 Directional Pad
6.5.8 Microphone
6.5.9 Fingerprint
6.5.10 Virtual Sensors
6.5.11 Snapshots
6.5.12 Record and Playback
6.5.13 Google Play
6.5.14 Settings
6.5.15 Help
6.6 Working with Snapshots
6.7 Configuring Fingerprint Emulation
6.8 The Emulator in Tool Window Mode
6.9 Common Android Settings
6.10 Creating a Resizable Emulator
6.11 Take the knowledge test
6.12 Summary
7. A Tour of the Android Studio User Interface
7.1 The Welcome Screen
7.2 The Menu Bar
7.3 The Main Window
7.4 The Tool Windows
7.5 The Tool Window Menus
7.6 Android Studio Keyboard Shortcuts
7.7 Switcher and Recent Files Navigation
7.8 Changing the Android Studio Theme
7.9 Take the knowledge test
7.10 Summary
8. Testing Android Studio Apps on a Physical Android Device
8.1 An Overview of the Android Debug Bridge (ADB)
8.2 Enabling USB Debugging ADB on Android Devices
8.2.1 macOS ADB Configuration
8.2.2 Windows ADB Configuration
8.2.3 Linux adb Configuration
8.3 Resolving USB Connection Issues
8.4 Enabling Wireless Debugging on Android Devices
8.5 Testing the adb Connection
8.6 Device Mirroring
8.7 Take the knowledge test
8.8 Summary
9. The Basics of the Android Studio Code Editor
9.1 The Android Studio Editor
9.2 Splitting the Editor Window
9.3 Code Completion
9.4 Statement Completion
9.5 Parameter Information
9.6 Parameter Name Hints
9.7 Code Generation
9.8 Code Folding
9.9 Quick Documentation Lookup
9.10 Code Reformatting
9.11 Finding Sample Code
9.12 Live Templates
9.13 Take the knowledge test
9.14 Summary
10. An Overview of the Android Architecture
10.1 The Android Software Stack
10.2 The Linux Kernel
10.3 Hardware Abstraction Layer
10.4 Android Runtime – ART
10.4.1 Dalvik and DEX
10.4.2 The ART and AOT
10.4.3 ART and the Linux kernel
10.5 Android Libraries
10.6 C/C++ Libraries
10.7 Native Development Kit
10.8 Application Framework
10.9 Applications
10.10 Take the knowledge test
10.11 Summary
11. An Introduction to Kotlin
11.1 What is Kotlin?
11.2 Kotlin and Java
11.3 Converting from Java to Kotlin
11.4 Kotlin and Android Studio
11.5 Experimenting with Kotlin
11.6 Semi-colons in Kotlin
11.7 Summary
12. Kotlin Data Types, Variables and Nullability
12.1 Kotlin data types
12.1.1 Integer data types
12.1.2 Floating point data types
12.1.3 Boolean data type
12.1.4 Character data type
12.1.5 String data type
12.1.6 Escape sequences
12.2 Mutable variables
12.3 Immutable variables
12.4 Declaring mutable and immutable variables
12.5 Data types are objects
12.6 Type annotations and type inference
12.7 Nullable type
12.8 The safe call operator
12.9 Not-null assertion
12.10 Nullable types and the let function
12.11 Late initialization (lateinit)
12.12 The Elvis operator
12.13 Type casting and type checking
12.14 Take the knowledge test
12.15 Summary
13. Kotlin Operators and Expressions
13.1 Expression syntax in Kotlin
13.2 The Basic assignment operator
13.3 Kotlin arithmetic operators
13.4 Augmented assignment operators
13.5 Increment and decrement operators
13.6 Equality operators
13.7 Boolean logical operators
13.8 Range operator
13.9 Bitwise operators
13.9.1 Bitwise inversion
13.9.2 Bitwise AND
13.9.3 Bitwise OR
13.9.4 Bitwise XOR
13.9.5 Bitwise left shift
13.9.6 Bitwise right shift
13.10 Take the knowledge test
13.11 Summary
14. Kotlin Control Flow
14.1 Looping control flow
14.1.1 The Kotlin for-in Statement
14.1.2 The while loop
14.1.3 The do ... while loop
14.1.4 Breaking from Loops
14.1.5 The continue statement
14.1.6 Break and continue labels
14.2 Conditional control flow
14.2.1 Using the if expressions
14.2.2 Using if ... else … expressions
14.2.3 Using if ... else if ... Expressions
14.2.4 Using the when statement
14.3 Take the knowledge test
14.4 Summary
15. An Overview of Kotlin Functions and Lambdas
15.1 What is a function?
15.2 How to declare a Kotlin function
15.3 Calling a Kotlin function
15.4 Single expression functions
15.5 Local functions
15.6 Handling return values
15.7 Declaring default function parameters
15.8 Variable number of function parameters
15.9 Lambda expressions
15.10 Higher-order functions
15.11 Take the knowledge test
15.12 Summary
16. The Basics of Object-Oriented Programming in Kotlin
16.1 What is an object?
16.2 What is a class?
16.3 Declaring a Kotlin class
16.4 Adding properties to a class
16.5 Defining methods
16.6 Declaring and initializing a class instance
16.7 Primary and secondary constructors
16.8 Initializer blocks
16.9 Calling methods and accessing properties
16.10 Custom accessors
16.11 Nested and inner classes
16.12 Companion objects
16.13 Take the knowledge test
16.14 Summary
17. An Introduction to Kotlin Inheritance and Subclassing
17.1 Inheritance, classes, and subclasses
17.2 Subclassing syntax
17.3 A Kotlin inheritance example
17.4 Extending the functionality of a subclass
17.5 Overriding inherited methods
17.6 Adding a custom secondary constructor
17.7 Using the SavingsAccount class
17.8 Take the knowledge test
17.9 Summary
18. Introducing Gemini in Android Studio
18.1 Introducing Gemini AI
18.2 Enabling Gemini in Android Studio
18.3 Gemini configuration
18.4 Asking Gemini questions
18.5 Question contexts
18.6 Inline code completion
18.7 Transforming and documenting code
18.8 Take the knowledge test
18.9 Summary
19. An Overview of Compose
19.1 Development before Compose
19.2 Compose declarative syntax
19.3 Compose is data-driven
19.4 Take the knowledge test
19.5 Summary
20. A Guide to Gradle Version Catalogs
20.1 Library and Plugin Dependencies
20.2 Project Gradle Build File
20.3 Module Gradle Build Files
20.4 Version Catalog File
20.5 Adding Dependencies
20.6 Library Updates
20.7 Take the knowledge test
20.8 Summary
21. Composable Functions Overview
21.1 What is a composable function?
21.2 Stateful vs. stateless composables
21.3 Composable function syntax
21.4 Composable hierarchy
21.5 Foundation and Material composables
21.6 Take the knowledge test
21.7 Summary
22. An Overview of Compose State and Recomposition
22.1 The basics of state
22.2 Introducing recomposition
22.3 Creating the StateExample project
22.4 Declaring state in a composable
22.5 Unidirectional data flow
22.6 State hoisting
22.7 How high to hoist?
22.8 Saving state through configuration changes
22.9 Take the knowledge test
22.10 Summary
23. An Introduction to Composition Local
23.1 Understanding CompositionLocal
23.2 Using CompositionLocal
23.3 Creating the CompLocalDemo project
23.4 Designing the layout
23.5 Adding the CompositionLocal state
23.6 Accessing the CompositionLocal state
23.7 Testing the design
23.8 Take the knowledge test
23.9 Summary
24. An Overview of Compose Slot APIs
24.1 Understanding slot APIs
24.2 Declaring a slot API
24.3 Calling slot API composables
24.4 Take the knowledge test
24.5 Summary
25. A Compose Slot API Tutorial
25.1 About the project
25.2 Creating the SlotApiDemo project
25.3 Preparing the MainActivity class file
25.4 Creating the MainScreen composable
25.5 Adding the ScreenContent composable
25.6 Creating the Checkbox composable
25.7 Implementing the ScreenContent slot API
25.8 Adding an Image drawable resource
25.9 Coding the TitleImage composable
25.10 Completing the MainScreen composable
25.11 Previewing the project
25.12 Summary
26. Using Modifiers in Compose
26.1 An overview of modifiers
26.2 Creating the ModifierDemo project
26.3 Creating a modifier
26.4 Modifier ordering
26.5 Adding modifier support to a composable
26.6 Common built-in modifiers
26.7 Combining modifiers
26.8 Take the knowledge test
26.9 Summary
27. Annotated Strings and Brush Styles
27.1 What are annotated strings?
27.2 Using annotated strings
27.3 Brush Text Styling
27.4 Creating the example project
27.5 An example SpanStyle annotated string
27.6 An example ParagraphStyle annotated string
27.7 A Brush style example
27.8 Take the knowledge test
27.9 Summary
28. Composing Layouts with Row and Column
28.1 Creating the RowColDemo project
28.2 Row composable
28.3 Column composable
28.4 Combining Row and Column composables
28.5 Layout alignment
28.6 Layout arrangement positioning
28.7 Layout arrangement spacing
28.8 Row and Column scope modifiers
28.9 Scope modifier weights
28.10 Take the knowledge test
28.11 Summary
29. Box Layouts in Compose
29.1 An introduction to the Box composable
29.2 Creating the BoxLayout project
29.3 Adding the TextCell composable
29.4 Adding a Box layout
29.5 Box alignment
29.6 BoxScope modifiers
29.7 Using the clip() modifier
29.8 Take the knowledge test
29.9 Summary
30. An Introduction to FlowRow and FlowColumn
30.1 FlowColumn and FlowRow
30.2 Maximum number of items
30.3 Working with main axis arrangement
30.4 Understanding cross-axis arrangement
30.5 Item alignment
30.6 Controlling item size
30.7 Take the knowledge test
30.8 Summary
31. A FlowRow and FlowColumn Tutorial
31.1 Creating the FlowLayoutDemo project
31.2 Generating random height and color values
31.3 Adding the Box Composable
31.4 Modifying the Flow arrangement
31.5 Modifying item alignment
31.6 Switching to FlowColumn
31.7 Using cross-axis arrangement
31.8 Adding item weights
31.9 Summary
32. Custom Layout Modifiers
32.1 Compose layout basics
32.2 Custom layouts
32.3 Creating the LayoutModifier project
32.4 Adding the ColorBox composable
32.5 Creating a custom layout modifier
32.6 Understanding default position
32.7 Completing the layout modifier
32.8 Using a custom modifier
32.9 Working with alignment lines
32.10 Working with baselines
32.11 Take the knowledge test
32.12 Summary
33. Building Custom Layouts
33.1 An overview of custom layouts
33.2 Custom layout syntax
33.3 Using a custom layout
33.4 Creating the CustomLayout project
33.5 Creating the CascadeLayout composable
33.6 Using the CascadeLayout composable
33.7 Take the knowledge test
33.8 Summary
34. A Guide to ConstraintLayout in Compose
34.1 An introduction to ConstraintLayout
34.2 How ConstraintLayout works
34.2.1 Constraints
34.2.2 Margins
34.2.3 Opposing constraints
34.2.4 Constraint bias
34.2.5 Chains
34.2.6 Chain styles
34.3 Configuring dimensions
34.4 Guideline helper
34.5 Barrier helper
34.6 Take the knowledge test
34.7 Summary
35. Working with ConstraintLayout in Compose
35.1 Calling ConstraintLayout
35.2 Generating references
35.3 Assigning a reference to a composable
35.4 Adding constraints
35.5 Creating the ConstraintLayout project
35.6 Adding the ConstraintLayout library
35.7 Adding a custom button composable
35.8 Basic constraints
35.9 Opposing constraints
35.10 Constraint bias
35.11 Constraint margins
35.12 The importance of opposing constraints and bias
35.13 Creating chains
35.14 Working with guidelines
35.15 Working with barriers
35.16 Decoupling constraints with constraint sets
35.17 Take the knowledge test
35.18 Summary
36. Working with IntrinsicSize in Compose
36.1 Intrinsic measurements
36.2 Max. vs Min. Intrinsic Size measurements
36.3 About the example project
36.4 Creating the IntrinsicSizeDemo project
36.5 Creating the custom text field
36.6 Adding the Text and Box components
36.7 Adding the top-level Column
36.8 Testing the project
36.9 Applying IntrinsicSize.Max measurements
36.10 Applying IntrinsicSize.Min measurements
36.11 Take the knowledge test
36.12 Summary
37. Coroutines and LaunchedEffects in Jetpack Compose
37.1 What are coroutines?
37.2 Threads vs. coroutines
37.3 Coroutine Scope
37.4 Suspend functions
37.5 Coroutine dispatchers
37.6 Coroutine builders
37.7 Jobs
37.8 Coroutines – suspending and resuming
37.9 Coroutine channel communication
37.10 Understanding side effects
37.11 Take the knowledge test
37.12 Summary
38. An Overview of Lists and Grids in Compose
38.1 Standard vs. lazy lists
38.2 Working with Column and Row lists
38.3 Creating lazy lists
38.4 Enabling scrolling with ScrollState
38.5 Programmatic scrolling
38.6 Sticky headers
38.7 Responding to scroll position
38.8 Creating a lazy grid
38.9 Take the knowledge test
38.10 Summary
39. A Compose Row and Column List Tutorial
39.1 Creating the ListDemo project
39.2 Creating a Column-based list
39.3 Enabling list scrolling
39.4 Manual scrolling
39.5 A Row list example
39.6 Summary
40. A Compose Lazy List Tutorial
40.1 Creating the LazyListDemo project
40.2 Adding list data to the project
40.3 Reading the XML data
40.4 Handling image loading
40.5 Designing the list item composable
40.6 Building the lazy list
40.7 Testing the project
40.8 Making list items clickable
40.9 Take the knowledge test
40.10 Summary
41. Lazy List Sticky Headers and Scroll Detection
41.1 Grouping the list item data
41.2 Displaying the headers and items
41.3 Adding sticky headers
41.4 Reacting to scroll position
41.5 Adding the scroll button
41.6 Testing the finished app
41.7 Take the knowledge test
41.8 Summary
42. A Compose Lazy Staggered Grid Tutorial
42.1 Lazy Staggered Grids
42.2 Creating the StaggeredGridDemo project
42.3 Adding the Box composable
42.4 Generating random height and color values
42.5 Creating the Staggered List
42.6 Testing the project
42.7 Switching to a horizontal staggered grid
42.8 Take the knowledge test
42.9 Summary
43. VerticalPager and HorizontalPager in Compose
43.1 The Pager composables
43.2 Working with pager state
43.3 About the PagerDemo project
43.4 Creating the PagerDemo project
43.5 Adding the book cover images
43.6 Adding the HorizontalPager
43.7 Creating the page content
43.8 Testing the pager
43.9 Adding the arrow buttons
43.10 Take the knowledge test
43.11 Summary
44. Compose Visibility Animation
44.1 Creating the AnimateVisibility project
44.2 Animating visibility
44.3 Defining enter and exit animations
44.4 Animation specs and animation easing
44.5 Repeating an animation
44.6 Different animations for different children
44.7 Auto-starting an animation
44.8 Implementing crossfading
44.9 Take the knowledge test
44.10 Summary
45. Compose State-Driven Animation
45.1 Understanding state-driven animation
45.2 Introducing animate as state functions
45.3 Creating the AnimateState project
45.4 Animating rotation with animateFloatAsState
45.5 Animating color changes with animateColorAsState
45.6 Animating motion with animateDpAsState
45.7 Adding spring effects
45.8 Working with keyframes
45.9 Combining multiple animations
45.10 Using the Animation Inspector
45.11 Take the knowledge test
45.12 Summary
46. Canvas Graphics Drawing in Compose
46.1 Introducing the Canvas component
46.2 Creating the CanvasDemo project
46.3 Drawing a line and getting the canvas size
46.4 Drawing dashed lines
46.5 Drawing a rectangle
46.6 Applying rotation
46.7 Drawing circles and ovals
46.8 Drawing gradients
46.9 Drawing arcs
46.10 Drawing paths
46.11 Drawing points
46.12 Drawing an image
46.13 Drawing text
46.14 Take the knowledge test
46.15 Summary
47. Working with ViewModels in Compose
47.1 What is Android Jetpack?
47.2 The “old” architecture
47.3 Modern Android architecture
47.4 The ViewModel component
47.5 ViewModel implementation using state
47.6 Connecting a ViewModel state to an activity
47.7 ViewModel implementation using LiveData
47.8 Observing ViewModel LiveData within an activity
47.9 Take the knowledge test
47.10 Summary
48. A Compose ViewModel Tutorial
48.1 About the project
48.2 Creating the ViewModelDemo project
48.3 Adding the ViewModel
48.4 Accessing DemoViewModel from MainActivity
48.5 Designing the temperature input composable
48.6 Designing the temperature input composable
48.7 Completing the user interface design
48.8 Testing the app
48.9 Summary
49. An Overview of Android SQLite Databases
49.1 Understanding database tables
49.2 Introducing database schema
49.3 Columns and data types
49.4 Database rows
49.5 Introducing primary keys
49.6 What is SQLite?
49.7 Structured Query Language (SQL)
49.8 Trying SQLite on an Android Virtual Device (AVD)
49.9 The Android Room persistence library
49.10 Take the knowledge test
49.11 Summary
50. Room Databases and Compose
50.1 Revisiting modern app architecture
50.2 Key elements of Room database persistence
50.2.1 Repository
50.2.2 Room database
50.2.3 Data Access Object (DAO)
50.2.4 Entities
50.2.5 SQLite database
50.3 Understanding entities
50.4 Data Access Objects
50.5 The Room database
50.6 The Repository
50.7 In-Memory databases
50.8 Database Inspector
50.9 Take the knowledge test
50.10 Summary
51. A Compose Room Database and Repository Tutorial
51.1 About the RoomDemo project
51.2 Creating the RoomDemo project
51.3 Modifying the build configuration
51.4 Building the entity
51.5 Creating the Data Access Object
51.6 Adding the Room database
51.7 Adding the repository
51.8 Adding the ViewModel
51.9 Designing the user interface
51.10 Writing a ViewModelProvider Factory class
51.11 Completing the MainScreen function
51.12 Testing the RoomDemo app
51.13 Using the Database Inspector
51.14 Take the knowledge test
51.15 Summary
52. An Overview of Navigation in Compose
52.1 Understanding navigation
52.2 Declaring a navigation controller
52.3 Declaring a navigation host
52.4 Adding destinations to the navigation graph
52.5 Navigating to destinations
52.6 Passing arguments to a destination
52.7 Working with bottom navigation bars
52.8 Summary
53. A Compose Navigation Tutorial
53.1 Creating the NavigationDemo project
53.2 About the NavigationDemo project
53.3 Declaring the navigation routes
53.4 Adding the home screen
53.5 Adding the welcome screen
53.6 Adding the profile screen
53.7 Creating the navigation controller and host
53.8 Implementing the screen navigation
53.9 Passing the user name argument
53.10 Testing the project
53.11 Take the knowledge test
53.12 Summary
54. A Compose Navigation Bar Tutorial
54.1 Creating the BottomBarDemo project
54.2 Declaring the navigation routes
54.3 Designing bar items
54.4 Creating the bar item list
54.5 Adding the destination screens
54.6 Creating the navigation controller and host
54.7 Designing the navigation bar
54.8 Working with the Scaffold component
54.9 Testing the project
54.10 Take the knowledge test
54.11 Summary
55. Detecting Gestures in Compose
55.1 Compose gesture detection
55.2 Creating the GestureDemo project
55.3 Detecting click gestures
55.4 Detecting taps using PointerInputScope
55.5 Detecting drag gestures
55.6 Detecting drag gestures using PointerInputScope
55.7 Scrolling using the scrollable modifier
55.8 Scrolling using the scroll modifiers
55.9 Detecting pinch gestures
55.10 Detecting rotation gestures
55.11 Detecting translation gestures
55.12 Take the knowledge test
55.13 Summary
56. An Introduction to Kotlin Flow
56.1 Understanding Flows
56.2 Creating the sample project
56.3 Adding a view model to the project
56.4 Declaring the flow
56.5 Emitting flow data
56.6 Collecting flow data as state
56.7 Transforming data with intermediaries
56.8 Collecting flow data
56.9 Adding a flow buffer
56.10 More terminal flow operators
56.11 Flow flattening
56.12 Combining multiple flows
56.13 Hot and cold flows
56.14 StateFlow
56.15 SharedFlow
56.16 Converting a flow from cold to hot
56.17 Take the knowledge test
56.18 Summary
57. A Jetpack Compose SharedFlow Tutorial
57.1 About the project
57.2 Creating the SharedFlowDemo project
57.3 Adding a view model to the project
57.4 Declaring the SharedFlow
57.5 Collecting the flow values
57.6 Testing the SharedFlowDemo app
57.7 Handling flows in the background
57.8 Take the knowledge test
57.9 Summary
58. Introducing Glance Widgets
58.1 Glance Overview
58.2 Glance app widget
58.3 Broadcast receiver
58.4 Widget provider info data
58.5 Size modes
58.6 Responding to user interaction
58.7 Updating a widget
58.8 Take the knowledge test
58.9 Summary
59. A Glance Widget Tutorial
59.1 About the project
59.2 Creating the GlanceWidget project
59.3 Adding image resources
59.4 The price data repository
59.5 Declaring the repository
59.6 Adding the Glance app widget
59.7 Declaring the widget receiver
59.8 Configuring the widget provider info metadata
59.9 Adding the widget receiver to the manifest
59.10 Testing the widget
59.11 Simulating price changes
59.12 Designing the widget
59.13 Adding size mode support
59.14 Responding to clicks
59.15 Take the knowledge test
59.16 Summary
60. An Android Biometric Authentication Tutorial
60.1 An overview of biometric authentication
60.2 Creating the biometric authentication project
60.3 Adding the biometric dependency
60.4 Configuring device fingerprint authentication
60.5 Adding the biometric permissions to the manifest file
60.6 Checking the security settings
60.7 Designing the user interface
60.8 Configuring the authentication callbacks
60.9 Starting the biometric prompt
60.10 Testing the project
60.11 Take the knowledge test
60.12 Summary
61. Working with the Google Maps Android API in Android Studio
61.1 The elements of the Google Maps Android API
61.2 Creating the Google Maps project
61.3 Creating a Google Cloud billing account
61.4 Creating a new Google Cloud project
61.5 Enabling the Google Maps SDK
61.6 Generating a Google Maps API key
61.7 Adding the API key to the Android Studio project
61.8 Adding the compose map dependency
61.9 Creating a map
61.10 Testing the application
61.11 Understanding geocoding and reverse geocoding
61.12 Specifying a map location
61.13 Changing the map type
61.14 Displaying map controls to the user
61.15 Handling map gesture interaction
61.15.1 Map zooming gestures
61.15.2 Map scrolling/panning gestures
61.15.3 Map tilt gestures
61.15.4 Map rotation gestures
61.16 Creating map markers
61.17 Controlling the map camera
61.18 Take the knowledge test
61.19 Summary
62. Creating, Testing, and Uploading an Android App Bundle
62.1 The Release Preparation Process
62.2 Android App Bundles
62.3 Register for a Google Play Developer Console Account
62.4 Configuring the App in the Console
62.5 Enabling Google Play App Signing
62.6 Creating a Keystore File
62.7 Creating the Android App Bundle
62.8 Generating Test APK Files
62.9 Uploading the App Bundle to the Google Play Developer Console
62.10 Exploring the App Bundle
62.11 Managing Testers
62.12 Rolling the App Out for Testing
62.13 Uploading New App Bundle Revisions
62.14 Analyzing the App Bundle File
62.15 Take the knowledge test
62.16 Summary
63. An Overview of Android In-App Billing
63.1 Preparing a project for In-App purchasing
63.2 Creating In-App products and subscriptions
63.3 Billing client initialization
63.4 Connecting to the Google Play Billing library
63.5 Querying available products
63.6 Starting the purchase process
63.7 Completing the purchase
63.8 Querying previous purchases
63.9 Take the knowledge test
63.10 Summary
64. An Android In-App Purchasing Tutorial
64.1 About the In-App purchasing example project
64.2 Creating the InAppPurchase project
64.3 Adding libraries to the project
64.4 Adding the App to the Google Play Store
64.5 Creating an In-App product
64.6 Enabling license testers
64.7 Creating a purchase helper class
64.8 Adding the StateFlow streams
64.9 Initializing the billing client
64.10 Querying the product
64.11 Handling purchase updates
64.12 Launching the purchase flow
64.13 Consuming the product
64.14 Restoring a previous purchase
64.15 Completing the MainActivity
64.16 Testing the app
64.17 Troubleshooting
64.18 Take the knowledge test
64.19 Summary
65. Working with Compose Theming
65.1 Material Design 2 vs. Material Design 3
65.2 Material Design 3 theming
65.3 Building a custom theme
65.4 Take the knowledge test
65.5 Summary
66. A Material Design 3 Theming Tutorial
66.1 Creating the ThemeDemo project
66.2 Designing the user interface
66.3 Building a new theme
66.4 Adding the Google font libraries
66.5 Adding the theme to the project
66.6 Testing dynamic colors
66.7 Take the knowledge test
66.8 Summary
67. An Overview of Gradle in Android Studio
67.1 An Overview of Gradle
67.2 Gradle and Android Studio
67.2.1 Sensible Defaults
67.2.2 Dependencies
67.2.3 Build Variants
67.2.4 Manifest Entries
67.2.5 APK Signing
67.2.6 ProGuard Support
67.3 The Property and Settings Gradle Build File
67.4 The Top-level Gradle Build File
67.5 Module Level Gradle Build Files
67.6 Configuring Signing Settings in the Build File
67.7 Running Gradle Tasks from the Command Line
67.8 Take the knowledge test
67.9 Summary
Index
1. Start Here
Welcome to this comprehensive guide to building Android applications using Jetpack Compose 1.7, Android Studio Ladybug, Material Design 3, and the Kotlin programming language. This book has been designed to teach developers the essential knowledge and skills to create modern, dynamic, and visually compelling applications.
We begin with foundational steps, including the setup of your development environment in Android Studio, followed by a detailed introduction to Kotlin, the language underpinning Android development. This section covers core aspects of Kotlin, such as data types, operators, control flow, functions, lambdas, and coroutines, establishing a strong basis in object-oriented programming principles.
With this foundation in place, we turn to Jetpack Compose, Google’s innovative toolkit for building native user interfaces. This book presents an in-depth exploration of Compose components and layout structures, including rows, columns, boxes, flows, pagers, and lists, alongside an overview of Android project architecture and Android Studio’s Compose development mode.
The following sections delve into more advanced topics, such as state management, modifiers, and navigation components—key elements in designing smooth and intuitive user interfaces. We also guide you through creating reusable layout components, securing applications with biometric authentication, and incorporating Google Maps functionality to enrich user engagement.
Furthermore, we cover specialized techniques, such as graphics rendering, animations, transitions, Kotlin Flows, and gesture handling. Practical data management solutions, including view models, Room database access, live data, and the Database Inspector, are discussed in depth. For developers interested in monetization, this guide also includes a dedicated section on implementing in-app billing.
The concluding chapters provide a comprehensive overview of app packaging and the publication process on the Google Play Store. Throughout the book, each concept is solidified through detailed, hands-on tutorials, complemented by downloadable source code to facilitate real-world application and access to over 55 online knowledge test quizzes.
With a basic understanding of programming, access to Android Studio and the Android SDK, and a Windows, Mac, or Linux system, you will be well-prepared to embark on this journey. It is our aim that, upon completion, you will be equipped with the skills necessary to design, build, and deploy professional-grade Android applications.
1.1 For Kotlin programmers
This book addresses the needs of existing Kotlin programmers and those new to Kotlin and Jetpack Compose app development. If you are familiar with the Kotlin programming language, you can probably skip the Kotlin-specific chapters.
1.2 For new Kotlin programmers
If you are new to Kotlin programming, the entire book is appropriate for you. Just start at the beginning and keep going.
1.3 Downloading the code samples
The source code and Android Studio project files for the examples contained in this book are available for download at:
https://www.payloadbooks.com/product/compose17/
The steps to load a project from the code samples into Android Studio are as follows:
1. Click on the Open button option from the Welcome to Android Studio dialog.
2. In the project selection dialog, navigate to and select the folder containing the project to be imported and click on OK.
1.4 Feedback
We want you to be satisfied with your purchase of this book. Therefore, if you find any errors in the book or have any comments, questions, or concerns, please contact us at [email protected].
1.5 Errata
While we make every effort to ensure the accuracy of the content of this book, inevitably, a book covering a subject area of this size and complexity may include some errors and oversights. Any known issues with the book will be outlined, together with solutions, at the following URL:
https://www.payloadbooks.com/compose17_errata
If you find an error not listed in the errata, email our technical support team at [email protected].
1.6 Take the knowledge tests
Look for this section at the end of most chapters and use the link or scan the QR code to take a knowledge quiz to test and reinforce your understanding of the covered topic. Use the following link to review the full list of tests available for this book:
https://www.answertopia.com/p9jf
2. Setting up an Android Studio Development Environment
Before any work can begin on developing an Android application, the first step is to configure a computer system to act as the development platform. This involves several steps consisting of installing the Android Studio Integrated Development Environment (IDE), including the Android Software Development Kit (SDK), the Kotlin plug-in and the OpenJDK Java development environment.
This chapter will cover the steps necessary to install the requisite components for Android application development on Windows, macOS, and Linux-based systems.
2.1 System requirements
Android application development may be performed on any of the following system types:
•Windows 8/10/11 64-bit
•macOS 10.14 or later running on Intel or Apple silicon
•Chrome OS device with Intel i5 or higher
•Linux systems with version 2.31 or later of the GNU C Library (glibc)
•Minimum of 8GB of RAM
•Approximately 8GB of available disk space
•1280 x 800 minimum screen resolution
2.2 Downloading the Android Studio package
Most of the work involved in developing applications for Android will be performed using the Android Studio environment. The content and examples in this book were created based on Android Studio Ladybug 2024.2.1 using the Android API 35 SDK (VanillaIceCream), which, at the time of writing, are the latest stable releases.
Android Studio is, however, subject to frequent updates, so a newer version may have been released since this book was published.
The latest release of Android Studio may be downloaded from the primary download page, which can be found at the following URL:
https://developer.android.com/studio/index.html
If this page provides instructions for downloading a newer version of Android Studio, there may be differences between this book and the software. A web search for “Android Studio Ladybug” should provide the option to download the older version if these differences become a problem. Alternatively, visit the following web page to find Android Studio Ladybug 2024.2.1 in the archives:
https://developer.android.com/studio/archive
2.3 Installing Android Studio
Once downloaded, the exact steps to install Android Studio differ depending on the operating system on which the installation is performed.
2.3.1 Installation on Windows
Locate the downloaded Android Studio installation executable file (named android-studio-<version>-windows.exe) in a Windows Explorer window and double-click on it to start the installation process, clicking the Yes button in the User Account Control dialog if it appears.
Once the Android Studio setup wizard appears, work through the various screens to configure the installation to meet your requirements in terms of the file system location into which Android Studio should be installed and whether or not it should be made available to other system users. When prompted to select the components to install, ensure that the Android Studio and Android Virtual Device options are all selected.
Although there are no strict rules on where Android Studio should be installed on the system, the remainder of this book will assume that the installation was performed into C:\Program Files\Android\Android Studio and that the Android SDK packages have been installed into the user’s AppData\Local\Android\sdk sub-folder. Once the options have been configured, click the Install button to begin the installation process.
On versions of Windows with a Start menu, the newly installed Android Studio can be launched from the entry added to that menu during the installation. The executable may be pinned to the taskbar for easy access by navigating to the Android Studio\bin directory, right-clicking on the studio64 executable, and selecting the Pin to Taskbar menu option (on Windows 11, this option can be found by selecting Show more options from the menu).
2.3.2 Installation on macOS
Android Studio for macOS is downloaded as a disk image (.dmg) file. Once the android-studio-<version>-mac.dmg file has been downloaded, locate it in a Finder window and double-click on it to open it, as shown in Figure 2-1:
Figure 2-1
To install the package, drag the Android Studio icon and drop it onto the Applications folder. The Android Studio package will then be installed into the Applications folder of the system, a process that will typically take a few seconds to complete.
To launch Android Studio, locate the executable in the Applications folder using a Finder window and double-click on it.
For future, easier access to the tool, drag the Android Studio icon from the Finder window and drop it onto the dock.
2.3.3 Installation on Linux
Having downloaded the Linux Android Studio package, open a terminal window, change directory to the location where Android Studio is to be installed, and execute the following command:
tar xvfz /<path to package>/android-studio-<version>-linux.tar.gz
Note that the Android Studio bundle will be installed into a subdirectory named android-studio. Therefore, assuming that the above command was executed in /home/demo, the software packages will be unpacked into /home/demo/android-studio.
To launch Android Studio, open a terminal window, change directory to the android-studio/bin sub-directory, and execute the following command:
./studio.sh
2.4 The Android Studio setup wizard
If you have previously installed an earlier version of Android Studio, the first time this new version is launched, a dialog may appear providing the option to import settings from a previous Android Studio version. If you have settings from a previous version and would like to import them into the latest installation, select the appropriate option and location. Alternatively, indicate that you do not need to import any previous settings and click the OK button to proceed.
If you are installing Android Studio for the first time, the initial dialog that appears once the setup process starts may resemble that shown in Figure 2-2 below:
Figure 2-2
If this dialog appears, click the Next button to display the Install Type screen (Figure 2-3). On this screen, select the Standard installation option before clicking Next.
Figure 2-3
On the Select UI Theme screen, select either the Darcula or Light theme based on your preferences. After making a choice, click Next, and review the options in the Verify Settings screen before proceeding to the License Agreement screen. Select each license category and enable the Accept checkbox. Finally, click the Finish button to initiate the installation.
After these initial setup steps have been taken, click the Finish button to display the Welcome to Android Studio screen using your chosen UI theme:
Figure 2-4
2.5 Installing additional Android SDK packages
The steps performed so far have installed the Android Studio IDE and the current set of default Android SDK packages. Before proceeding, it is worth taking some time to verify which packages are installed and to install any missing or updated packages.
This task can be performed by clicking on the More Actions link within the welcome dialog and selecting the SDK Manager option from the drop-down menu.Once invoked, the Android SDK screen of the Settings dialog will appear as shown in Figure 2-5:
Figure 2-5
Google pairs each release of Android Studio with a maximum supported Application Programming Interface (API) level of the Android SDK. In the case of Android Studio Ladybug, this is Android VanillaIceCream (API Level 35). This information can be confirmed using the following link:
https://developer.android.com/studio/releases#api-level-support
Immediately after installing Android Studio for the first time, it is likely that only the latest supported version of the Android SDK has been installed. To install older versions of the Android SDK, select the checkboxes corresponding to the versions and click the Apply button. The rest of this book assumes that the Android VanillaIceCream (API Level 35) SDK is installed.
Most of the examples in this book will support older versions of Android as far back as Android 8.0 (Oreo). This ensures that the apps run on a wide range of Android devices. Within the list of SDK versions, enable the checkbox next to Android 8.0 (Oreo) and click the Apply button. Click the OK button to install the SDK in the resulting confirmation dialog. Subsequent dialogs will seek the acceptance of licenses and terms before performing the installation. Click Finish once the installation is complete.
It is also possible that updates will be listed as being available for the latest SDK. To access detailed information about the packages that are ready to be updated, enable the Show Package Details option located in the lower right-hand corner of the screen. This will display information similar to that shown in Figure 2-6:
Figure 2-6
The above figure highlights the availability of an update. To install the updates, enable the checkbox to the left of the item name and click the Apply button.
In addition to the Android SDK packages, several tools are also installed for building Android applications. To view the currently installed packages and check for updates, remain within the SDK settings screen and select the SDK Tools tab as shown in Figure 2-7:
Figure 2-7
Within the Android SDK Tools screen, make sure that the following packages are listed as Installed in the Status column:
•Android SDK Build-tools
•Android Emulator
•Android SDK Platform-tools
•Google Play Services
•Intel x86 Emulator Accelerator (HAXM installer)*
•Google USB Driver (Windows only)
•Layout Inspector image server for API 31-35
*Note that the Intel x86 Emulator Accelerator (HAXM installer) requires an Intel processor with VT-x support enabled. It cannot be installed on Apple silicon-based Macs or AMD-based PCs.
If any of the above packages are listed as Not Installed or requiring an update, select the checkboxes next to those packages and click the Apply button to initiate the installation process. If the HAXM emulator settings dialog appears, select the recommended memory allocation:
Figure 2-8
Once the installation is complete, review the package list and ensure that the selected packages are listed as Installed in the Status column. If any are listed as Not installed, make sure they are selected and click the Apply button again.
2.6 Installing the Android SDK Command-line Tools
Android Studio includes tools that allow some tasks to be performed from your operating system command line. To install these tools on your system, open the SDK Manager, select the SDK Tools tab, and locate the Android SDK Command-line Tools (latest) package as shown in Figure 2-9:
Figure 2-9
If the command-line tools package is not already installed, enable it and click Apply, followed by OK to complete the installation. When the installation completes, click Finish and close the SDK Manager dialog.
For the operating system on which you are developing to be able to find these tools, it will be necessary to add them to the system’s PATH environment variable.
Regardless of your operating system, you will need to configure the PATH environment variable to include the following paths (where <path_to_android_sdk_installation> represents the file system location into which you installed the Android SDK):
<path_to_android_sdk_installation>/sdk/cmdline-tools/latest/bin
<path_to_android_sdk_installation>/sdk/platform-tools
You can identify the location of the SDK on your system by launching the SDK Manager and referring to the Android SDK Location: field located at the top of the settings panel, as highlighted in Figure 2-10:
Figure 2-10
Once the location of the SDK has been identified, the steps to add this to the PATH variable are operating system dependent:
2.6.1 Windows 8.1
1. On the start screen, move the mouse to the bottom right-hand corner of the screen and select Search from the resulting menu. In the search box, enter Control Panel. When the Control Panel icon appears in the results area, click on it to launch the tool on the desktop.
2. Within the Control Panel, use the Category menu to change the display to Large Icons. From the list of icons, select the one labeled System.
3. In the Environment Variables dialog, locate the Path variable in the System variables list, select it, and click the Edit… button. Using the New button in the edit dialog, add two new entries to the path. For example, assuming the Android SDK was installed into C:\Users\demo\AppData\Local\Android\Sdk, the following entries would need to be added:
C:\Users\demo\AppData\Local\Android\Sdk\cmdline-tools\latest\bin
C:\Users\demo\AppData\Local\Android\Sdk\platform-tools
4. Click OK in each dialog box and close the system properties control panel.
Open a command prompt window by pressing Windows + R on the keyboard and entering cmd into the Run dialog. Within the Command Prompt window, enter:
echo %Path%
The returned path variable value should include the paths to the Android SDK platform tools folders. Verify that the platform-tools value is correct by attempting to run the adb tool as follows:
adb
The tool should output a list of command-line options when executed.
Similarly, check the tools path setting by attempting to run the AVD Manager command-line tool (don’t worry if the avdmanager tool reports a problem with Java - this will be addressed later):
avdmanager
If a message similar to the following message appears for one or both of the commands, it is most likely that an incorrect path was appended to the Path environment variable:
'adb' is not recognized as an internal or external command,
operable program or batch file.
2.6.2 Windows 10
Right-click on the Start menu, select Settings from the resulting menu and enter “Edit the system environment variables” into the Find a setting text field. In the System Properties dialog, click the Environment Variables... button. Follow the steps outlined for Windows 8.1 starting from step 3.
2.6.3 Windows 11
Right-click on the Start icon located in the taskbar and select Settings from the resulting menu. When the Settings dialog appears, scroll down the list of categories and select the “About” option. In the About screen, select Advanced system settings from the Related links section. When the System Properties window appears, click the Environment Variables... button. Follow the steps outlined for Windows 8.1 starting from step 3.
2.6.4 Linux
This configuration can be achieved on Linux by adding a command to the .bashrc file in your home directory (specifics may differ depending on the particular Linux distribution in use). Assuming that the Android SDK bundle package was installed into /home/demo/Android/sdk, the export line in the .bashrc file would read as follows:
export PATH=/home/demo/Android/sdk/platform-tools:/home/demo/Android/sdk/cmdline-tools/latest/bin:/home/demo/android-studio/bin:$PATH
Note also that the above command adds the android-studio/bin directory to the PATH variable. This will enable the studio.sh script to be executed regardless of the current directory within a terminal window.
2.6.5 macOS
Several techniques may be employed to modify the $PATH environment variable on macOS. Arguably the cleanest method is to add a new file in the /etc/paths.d directory containing the paths to be added to $PATH. Assuming an Android SDK installation location of /Users/demo/Library/Android/sdk, the path may be configured by creating a new file named android-sdk in the /etc/paths.d directory containing the following lines:
/Users/demo/Library/Android/sdk/cmdline-tools/latest/bin
/Users/demo/Library/Android/sdk/platform-tools
Note that since this is a system directory, it will be necessary to use the sudo command when creating the file. For example:
sudo vi /etc/paths.d/android-sdk
2.7 Android Studio memory management
Android Studio is a large and complex software application with many background processes. Although Android Studio has been criticized in the past for providing less than optimal performance, Google has made significant performance improvements in recent releases and continues to do so with each new version. These improvements include allowing the user to configure the amount of memory used by both the Android Studio IDE and the background processes used to build and run apps. This allows the software to take advantage of systems with larger amounts of RAM.
If you are running Android Studio on a system with sufficient unused RAM to increase these values (this feature is only available on 64-bit systems with 5GB or more of RAM) and find that Android Studio performance appears to be degraded, it may be worth experimenting with these memory settings. Android Studio may also notify you that performance can be increased via a dialog similar to the one shown below:
Figure 2-11
To view and modify the current memory configuration, select the File -> Settings... main menu option (Android Studio -> Settings... on macOS) and, in the resulting dialog, select Appearance & Behavior followed by the Memory Settings option listed under System Settings in the left-hand navigation panel, as illustrated in Figure 2-12 below:
Figure 2-12
When changing the memory allocation, be sure not to allocate more memory than necessary or than your system can spare without slowing down other processes.
The IDE heap size setting adjusts the memory allocated to Android Studio and applies regardless of the currently loaded project. On the other hand, when a project is built and run from within Android Studio, several background processes (referred to as daemons) perform the task of compiling and running the app. When compiling and running large and complex projects, build time could be improved by adjusting thedaemon heap settings. Unlike the IDE heap settings, these daemon settings apply only to the current project and can only be accessed when a project is open in Android Studio. To display the SDK Manager from within an open project, select the Tools -> SDK Manager... menu option from the main menu.
2.8 Updating Android Studio and the SDK
From time to time, new versions of Android Studio and the Android SDK are released. New versions of the SDK are installed using the Android SDK Manager. Android Studio will typically notify you when an update is ready to be installed.
To manually check for Android Studio updates, use the Help -> Check for Updates... menu option from the Android Studio main window (Android Studio -> Check for Updates... on macOS).
2.9 Summary
Before beginning the development of Android-based applications, the first step is to set up a suitable development environment. This consists of the Android SDKs and Android Studio IDE (which also includes the OpenJDK development environment). This chapter covers the steps necessary to install these packages on Windows, macOS, and Linux.