Head First Android Development: A Learner’s Guide to Building Android Apps with Kotlin, 3rd Edition
- Length: 932 pages
- Edition: 3
- Language: English
- Publisher: O'Reilly Media
- Publication Date: 2021-12-07
- ISBN-10: 149207652X
- ISBN-13: 9781492076520
- Sales Rank: #140265 (See Top 100 Books)
What will you learn from this book?
If you have an idea for a killer Android app, this fully revised and updated edition will get you up and running in a jiffy. You’ll go beyond syntax and how-to manuals and learn how to think like a great Android developer. This hands-on book teaches you everything from designing user interfaces to building multi-screen apps that persist data in a database. It covers the latest features of Android Jetpack, including Jetpack Compose. It’s like having an experienced Android developer sitting right next to you! If you have some Kotlin know-how, you’re ready to get started.
What’s so special about this book?
If you’ve read a Head First book, you know what to expect: a visually rich format designed for the way your brain works. If you haven’t, you’re in for a treat. With this book, you’ll learn Git through a multisensory experience that engages your mind rather than a text-heavy approach that puts you to sleep.
Authors of Head First Android Development Table of Contents (the real thing) How to use this book: Intro Who is this book for? Who should probably back away from this book? We know what you’re thinking We know what your brain is thinking Metacognition: thinking about thinking Here’s what WE did Here’s what YOU can do to bend your brain into submission Read me The truly awesome technical review team Acknowledgments O’Reilly Online Learning 1. Getting Started: Diving In Welcome to Androidville Activities define what the app does Layouts define what each screen looks like There may be extra files too Activities and layouts form the backbone of your app Here’s what we’re going to do Android Studio: your development environment You need to install Android Studio Install Android Studio Let’s build a basic app How to build the app 1. Create a new project 2. Select a project template 3. Configure your project You’ve created your first Android project Dissecting your new project The folder structure includes different types of files Introducing the key files in your project Edit code with the Android Studio editors The code editor The design editor The story so far How to run the app on a physical device 1. Enable USB debugging on your device 2. Set up your computer to detect the device 3. Use a USB cable to plug your device into your computer 4. Run the app How to run the app on a virtual device Create an Android Virtual Device (AVD) Open the Android Virtual Device Manager Select the hardware Select a system image Verify the AVD configuration The virtual device gets created Run the app on the AVD Compile, package, deploy, run Test Drive What just happened? Let’s refine the app The app has one activity and one layout The activity controls what the app does The layout controls the app’s appearance What’s in the layout? The design editor The code editor activity_main.xml has two elements Update the text displayed in the layout What the code does Test Drive Your Android Toolbox 2. Building Interactive Apps: Apps That Do Something Let’s build a Beer Adviser app Here’s what we’re going to do Create the project We’ve created a default activity and layout A closer look at the design editor Add a button using the design editor Changes in the design editor are reflected in the XML activity_main.xml has a new button Buttons and text views are subclasses of the same Android View class A closer look at the layout code The <LinearLayout> element The <Button> element The <TextView> element Let’s update the layout XML The XML changes are reflected in the design editor Test Drive There are warnings in the layout… …because there’s hardcoded text Put text in a String resource file Android Studio helps you extract String resources Extract the String resource A String resource has been added to strings.xml activity_main.xml uses the String resource You also can extract String resources manually Add and use a new String resource Test Drive Add values to the spinner Adding an array resource is similar to adding a String Add the string-array to strings.xml Get the spinner to display the array’s values The full code for activity_main.xml Test Drive We need to make the app interactive What the MainActivity code looks like A button can listen for on-click events… …using an OnClickListener Get a reference to the button… …and call its setOnClickListener method Pass a lambda to the setOnClickListener method How to edit a text view’s text How to get the spinner’s value Pool Puzzle Pool Puzzle Solution The updated code for MainActivity.kt What happens when you run the code Test Drive Add the getBeers() method Activity Magnets Activity Magnets Solution The full code for MainActivity.kt What happens when you run the code Test Drive Your Android Toolbox 3. Layouts: Being a layout It all starts with a layout Android has different types of layout Use the best layout for your screen design Let’s build a linear layout Create a new project How to define a linear layout Orientation can be vertical or horizontal Use padding to add space to the layout’s edges The layout code so far An edit text lets you enter text Add views to the layout XML Make a view streeeeetch by adding weight How to add weight to one view How to add weight to multiple views The gravity attribute controls the position of a view’s contents Values you can use with the android:gravity attribute Layout Magnets Layout Magnets Solution The story so far layout-gravity controls the position of a view within a layout More values you can use with the android:layout-gravity attribute Use margins to add space between views The full linear layout code Test Drive BE the Layout BE the Layout Solution Your activity code tells Android which layout it uses The layout’s views are inflated into objects Layout inflation: an example A frame layout stacks its views Create a new project How to define a frame layout Add an image to your project A frame layout stacks views in the order they appear in the layout XML Test Drive All layouts are a type of ViewGroup… …and a ViewGroup is a type of View A scroll view inserts a vertical scrollbar How to add a scroll view Test Drive Your Android Toolbox 4. Constraint Layouts: Draw Up a Blueprint Nested layouts revisited Nesting layouts comes at a price Introducing the constraint layout You design constraint layouts VISUALLY Constraint layouts are part of Android Jetpack Here’s what we’re going to do Create a new project Use Gradle to include Jetpack libraries The project build.gradle needs a Google repository line The app build.gradle includes the constraint layout’s library Let’s add a constraint layout to activity_main.xml Show the layout in the blueprint Add a button to the blueprint Position views using constraints We’ll add a horizontal constraint to the button Add a vertical constraint too Use opposing constraints to center views You can delete constraints you no longer need Remove constraints with the constraint widget You can use it to add margins too Changes to the blueprint appear in the XML Views can have bias Test Drive You can change a view’s size Make the view just big enough Match the view’s constraints BE the Constraint BE the Constraint Solution Most layouts need multiple views Add a second button to the blueprint You can connect views to other views You can align views too Align views using guidelines Guidelines have a fixed position Create a movable barrier Let’s build a layout that uses a barrier Add a horizontal barrier Place the barrier beneath the views Constrain a button under the barrier The full code for activity_main.xml Test Drive Use a chain to control a linear group of views We’re going to create a horizontal chain The chain will use three buttons Align the views we’re going to chain Create the horizontal chain There are different styles of chain Spread spaces out views between the blueprint’s edges Spread inside moves the first and last view to the edges Packed moves the views together Test Drive A flow is like a multi-line chain How to add a flow You can control the flow’s appearance Use “chain” to create a multi-line chain Use “aligned” to line up the views The full code for activity_main.xml Test Drive Your Android Toolbox 5. The Activity Lifecycle: Being an Activity How do activities really work? Introducing the Stopwatch app Create a new project Add String resources for the text labels The layout includes a Chronometer view The full code for activity_main.xml The activity code controls the stopwatch The Chronometer’s key properties and methods The base property The start() method The stop() method The full code for MainActivity.kt What happens when you run the app Test Drive But there’s just one problem… What happens when the app runs Rotating the screen changes the device configuration An activity’s states The activity lifecycle: from create to destroy Your activity inherits the lifecycle methods Save the current state in a Bundle Add values using put methods Retrieve values using get methods Save the state using onSaveInstanceState() Restore the state using onCreate() The updated MainActivity.kt code What happens when you run the app Test Drive Activity Magnets Activity Magnets Solution There’s more to an activity’s life than create and destroy Start, stop, and restart The visible lifecycle We need to implement two more lifecycle methods Implement onStop() to pause the stopwatch Restart the stopwatch when the app becomes visible The updated MainActivity.kt code What happens when you run the app Test Drive What if an activity is only partially visible? The foreground lifecycle Pause the stopwatch if the activity’s paused The complete MainActivity.kt code What happens when you run the app Test Drive Your handy guide to the activity lifecycle methods BE the Activity BE the Activity Solution Your Android Toolbox 6. Fragments and Navigation: Finding Your Way Most apps need more than one screen Each screen is a fragment WelcomeFragment MessageFragment EncryptFragment Navigate between screens using the Navigation component Here’s what we’re going to do Create a new project Add some String resources Add WelcomeFragment to the project What fragment code looks like Fragment code looks similar to activity code The fragment’s onCreateView() method Inflate the fragment’s layout, and return it Fragment layout code looks like activity layout code You display a fragment in a FragmentContainerView Update the activity_main.xml code The full code for MainActivity.kt What the code does Test Drive Pool Puzzle Pool Puzzle Solution Create MessageFragment Update MessageFragment’s layout Update MessageFragment.kt Use the Navigation component to navigate between fragments Use Gradle to add the Navigation component to your project Add a version number to the project build.gradle file Add a dependency to the app build.gradle file Create a navigation graph Add fragments to the navigation graph Connect fragments using an action Every action needs a unique ID Navigation graphs are XML resources Add a navigation host to the layout using a FragmentContainerView Add a NavHostFragment to activity_main.xml We need to navigate between the fragments Add an OnClickListener to the button Fragment OnClickListener code is a little different Get a navigation controller Tell it where to navigate with an action The full code for WelcomeFragment.kt What happens when the app runs Test Drive Your Android Toolbox 7. Safe Args: Passing Information The Secret Message app navigates between fragments MessageFragment needs to pass the message to a new fragment Here’s what we’re going to do Create EncryptFragment… …and update its layout Update EncryptFragment.kt Add EncryptFragment to the navigation graph The updated nav_graph.xml code MessageFragment needs to navigate to EncryptFragment Test Drive Add Safe Args to the build.gradle files Add a classpath to the project build.gradle file Add the plug-in to the app build.gradle file EncryptFragment needs to accept a String argument The updated nav_graph.xml code MessageFragment needs to pass a message to EncryptFragment You can pass arguments to navigation actions Safe Args generates Directions classes Use a Directions class to add arguments to actions Update the MessageFragment.kt code EncryptFragment needs to get the argument’s value Use an Args class to retrieve arguments We need to encrypt the message The full code for EncryptFragment.kt What happens when the app runs Test Drive Navigation Magnets Navigation Magnets Solution What if the user wants to go back? We could change the back behavior Welcome to the back stack A back stack scenario Use the navigation graph to pop fragments off the back stack The updated nav_graph.xml code Test Drive BE the Safe Args Plug-in BE the Safe Args Plug-in Solution Your Android Toolbox 8. Navigation ui: Going Places Different apps, different structures Android includes navigation UI components An app bar The bottom navigation bar A navigation drawer How the CatChat app will work Here’s what we’re going to do Create a new project A default app bar gets added… …by applying a theme The CatChat app will use a Material theme The app build.gradle file needs a Material library dependency Apply a theme in AndroidManifest.xml Define styles in style resource files Styles can override theme colors Color resource files define a set of colors Replace the default app bar with a toolbar Remove the default app bar using a theme A toolbar is a type of View Add the toolbar to activity_main.xml Where did the app name go? Set the toolbar as MainActivity’s app bar Test Drive Let’s use the toolbar to navigate How toolbar navigation will work Create InboxFragment Create HelpFragment We’ll use the Navigation component to navigate to HelpFragment Add a version number to the project build.gradle file Add dependencies to the app build.gradle file Add the fragments to a navigation graph Add a navigation host to activity_main.xml Specify items in the toolbar with a menu resource file Let’s add a Help item to the menu onCreateOptionsMenu() adds menu items to the toolbar Respond to menu item clicks with onOptionsItemSelected() We need to configure the toolbar Configure the toolbar using an AppBarConfiguration The full code for MainActivity.kt What happens when the app runs Test Drive BE the Menu BE the Menu Solution Most types of UI navigation work with the Navigation component How the bottom navigation bar will work Create SentItemsFragment Add SentItemsFragment to the Navigation graph The bottom navigation bar needs a new menu resource file A bottom navigation bar is a type of View The full code for activity_main.xml Link the bottom navigation bar to the navigation controller The updated code for MainActivity.kt Test Drive A navigation drawer lets you display many navigation items Let’s replace the bottom navigation bar with a navigation drawer Navigation drawers deconstructed The drawer gets its items from a menu Add the support section… …as a separate submenu Highlight the selected item with groups The full code for menu_main.xml Create the navigation drawer’s header Add the image file… …and update the nav_header.xml code How to create a navigation drawer The full code for activity_main.xml We’ve added a navigation drawer to the layout Configure the toolbar’s drawer icon… …and link the drawer to the navigation controller The full code for MainActivity.kt Test Drive Layout Magnets Layout Magnets Solution Your Android Toolbox 9. Material Views: A Material World Material is used throughout Androidville The Bits and Pizzas app Here’s what we’ll do Create the Bits and Pizzas project Add a Material library dependency to the app build.gradle file Create OrderFragment Display OrderFragment in MainActivity’s layout Replace the default app bar with a toolbar Fragments don’t have a setSupportActionBar() method We’ve added the toolbar…now what? We want the toolbar to respond to scrolls The coordinator layout coordinates animations between views The app bar layout enables toolbar animation Tell the toolbar how to respond to scroll events A nested scroll view makes layout content scrollable The full code for fragment_order.xml Test Drive BE the Layout BE the Layout Solution Let’s create a collapsing toolbar How to create a plain collapsing toolbar How to add an image to a collapsing toolbar Add a restaurant image drawable The full code for fragment_order.xml Test Drive Layout Magnets We need to build OrderFragment’s main content Choose a pizza type using a radio button Radio buttons are a type of compound button A chip is a type of flexible compound button Add multiple chips to a chip group Use isChecked to find out if a chip is checked A FAB is a floating action button You can anchor a FAB to a collapsing toolbar We need to build OrderFragment’s layout The full code for fragment_order.xml Test Drive Let’s make the FAB respond to clicks Add an OnClickListener to the FAB Find out if a pizza type has been selected A toast is a simple pop-up message Add a toast to the FAB OnClickListener Display the pizza order in a snackbar Snackbars can have actions The snackbar code for the pizza order The full code for OrderFragment.kt Test Drive Pool Puzzle Pool Puzzle Solution Layout Magnets Solution Your Android Toolbox 10. View Binding: Bound Together Behind the scenes of findViewById() findViewById() looks for a view in the view hierarchy There’s a downside to findViewById() View binding to the rescue View binding is safer and more efficient than findViewById() Here’s how we’ll use view binding The Stopwatch app revisited Enable view binding in the app build.gradle file Enabling view binding generates code for each layout How to add view binding to an activity Use the binding property to interact with views The layout code The activity code The full code for MainActivity.kt What the code does Test Drive Activity Magnets Fragments can use view binding too (but the code’s a little different) Let’s implement view binding in the Bits and Pizzas app Enable view binding for Bits and Pizzas Binding classes are generated for every layout Fragment view binding code is a little different Activities can access views from onCreate() Fragments can access views from onCreateView() to onDestroyView() What fragment view binding code looks like _binding refers to the binding object… ...and the binding property provides non-null access to it The full code for OrderFragment.kt Test Drive Activity Magnets Solution Your Android Toolbox 11. View Models: Model Behavior Configuration changes revisited There are other problems, too Introducing the view model Why use a view model? What the guessing game will do How the app will be structured Here’s what we’re going to do Create the Guessing Game project Update the project build.gradle file… …and update the app build.gradle file too The Guessing Game app has two fragments Create GameFragment… …and then create ResultFragment How navigation should work Create the navigation graph Update the navigation graph Display the current fragment in MainActivity’s layout Update GameFragment’s layout What GameFragment needs to do The GameFragment.kt code Update ResultFragment’s layout We also need to update ResultFragment.kt The ResultFragment.kt code What happens when the app runs Test Drive The game loses state when the screen rotates A view model holds business logic Add a view model dependency to the app build.gradle file… …and create a view model The full code for GameViewModel.kt Create a GameViewModel object Use a ViewModelProvider to create view models The updated code for GameFragment.kt What happens when the app runs Test Drive BE the View Model We’ve added a view model for GameFragment ResultFragment needs a view model too ResultViewModel needs to hold the result We need to link ResultViewModel to ResultFragment A view model factory creates view models Create the ResultViewModelFactory class Use the factory to create the view model The updated code for ResultFragment.kt What happens when the app runs Test Drive View Model Magnets View Model Magnets Solution BE the View Model Solution Your Android Toolbox 12. Live Data: Leaping into Action The Guessing Game app revisited The fragments decide when to update views Let the view model say when a value’s changed Here’s what we’re going to do Add a live data dependency to the app build.gradle file GameViewModel and GameFragment need to use live data Which view model properties should use live data? Live data objects use a value property The value property can be null The full code for GameViewModel.kt The fragment observes the view model properties and reacts to changes. The full code for GameFragment.kt What happens when the app runs Test Drive Fragments can update GameViewModel’s properties Keep your privates private The full code for GameViewModel.kt What happens when the app runs Test Drive GameFragment still includes game logic Make GameViewModel decide when the game is over Pool Puzzle Pool Puzzle Solution The full code for GameViewModel.kt Make GameFragment observe the new property What happens when the app runs Fragment Magnets Fragment Magnets Solution Test Drive Your Android Toolbox 13. Data Binding: Building Smart Layouts Back to the Guessing Game app The fragments update the views in their layouts We can make the views update themselves instead Here’s what we’re going to do Enable data binding in the app build.gradle file ResultFragment updates the text in its layout How we’ll implement data binding 1. Add <layout> and <data> elements 2. Set the layout’s data binding variable 3. Use the layout’s data binding variable to access the view model The full code for fragment_result.xml The full code for ResultFragment.kt What happens when the app runs Test Drive Layout Magnets Layout Magnets Solution GameFragment can use data binding too Add <layout> and <data> elements to fragment_game.xml Use the data binding variable to set the layout’s text Two of the views need to show extra text String resources revisited String resources can have arguments Add two new String resources to strings.xml The layout can pass parameters to String resources The full code for fragment_game.xml We need to set the gameViewModel variable We also need to make the data binding use live data The full code for GameFragment.kt What happens when the app runs Test Drive You can use data binding to call methods Add finishGame() to GameViewModel.kt Use data binding to make a button call a method when clicked The full code for fragment_game.xml What happens when the app runs Test Drive Pool Puzzle Fireside Chats We can switch off view binding Switch off view binding in the app’s build.gradle file Test Drive Binding-Cross Binding-Cross Solution Pool Puzzle Solution Your Android Toolbox 14. Room Databases: Room with a View Most apps need to store data Apps can persist data using a database How the app will be structured Room is a database library that sits on top of SQLite Room apps are usually structured using MVVM Here’s what we’re going to do Create the Tasks project Add a variable to the project build.gradle file… …and update the app build.gradle file, too Create TasksFragment Update TasksFragment.kt Update fragment_tasks.xml Display TasksFragment in MainActivity’s layout… …and check the MainActivity.kt code How Room databases are created 1. A database class 2. Data classes for the tables 3. Interfaces for data access We’ll store tasks data in a table You define tables with an annotated data class Create the Task data class Specify a table name with @Entity Specify the primary key with @PrimaryKey Specify column names with @ColumnInfo The full code for Task.kt Use an interface to specify data operations Create the TaskDao interface Use @Dao to mark the interface for data access Use @Insert to insert a record Use @Update to update a record Use @Delete to delete a record Use @Query for everything else The full code for TaskDao.kt Create a TaskDatabase abstract class Annotate the class with @Database Add properties for any DAO interfaces Create and return an instance of the database The full code for TaskDatabase.kt MVVM revisited We’ve completed all the Model code… …so let’s move on to the ViewModel Create TasksViewModel Database operations can run in slooooow-moooo We’ll use coroutines to run data access code in the background 1. Mark TaskDao’s methods with suspend 2. Launch the insert() method in the background TasksViewModel needs a view model factory Create TasksViewModelFactory TasksViewModelFactory needs a TaskDao The TaskDatabase code has a TaskDao property The updated code for TasksFragment.kt TasksFragment can use data binding We’ll use data binding to insert a record Set TasksViewModel’s newTaskName property Call TasksViewModel’s addTask() method The full fragment_tasks.xml code The full TasksFragment.kt code What happens when the code runs Test Drive TasksFragment needs to display records Use getAll() to get all tasks from the database A LiveData<List<Task>> is a more complex type Use Transformations.map() to transform live data objects Let’s update the TasksViewModel code We’ll bind the tasksString property to the layout’s text view We need to make the layout respond to live data updates The full TasksFragment.kt code What happens when the code runs Test Drive Mixed Messages Mixed Messages Solution Your Android Toolbox 15. Recycler Views: Reduce, Reuse, Recycle What the Tasks app currently looks like We can turn the list into a recycler view Why use a recycler view? Recycler views get their data from an adapter Here’s what we’re going to do Add a recycler view dependency to the app build.gradle file Tell the recycler view how to display each item… …by defining a layout file The adapter adds data to the recycler view Create the adapter file Tell the adapter what data it should work with Override the getItemCount() method Define the adapter’s view holder Override the onCreateViewHolder() method Add data to the layout’s view The full code for TaskItemAdapter.kt The adapter code is complete We need to display the recycler view How to add a recycler view to a layout The full code for fragment_tasks.xml Tell the recycler view to use the adapter The updated code for TasksFragment.kt We’ve added a recycler view to TasksFragment’s layout We’ll make TasksFragment add task data to TaskItemAdapter Update the TasksViewModel.kt code TasksFragment needs to update TaskItemAdapter’s data property The full code for TasksFragment.kt We’ve finished writing all the recycler view code What happens when the code runs Test Drive Adapter Magnets Adapter Magnets Solution Recycler views are very flexible Recycler view 2.0 Add a card view dependency to the app build.gradle file How to create a card view The full code for task_item.xml The adapter’s view holder needs to work with the new layout code The full code for TaskItemAdapter.kt What the recycler view looks like so far The layout manager gallery Display items in a horizontal row Use GridLayoutManager to display items in a grid Arrange items in a staggered grid Update fragment_tasks.xml to arrange items in a grid What happens when the code runs Test Drive Pool Puzzle Pool Puzzle Solution Your Android Toolbox 16. Diffutil and Data Binding: Life in the Fast Lane The recycler view displays task data correctly… …but when the data’s updated, the recycler view jumps The Tasks app revisited How the recycler view gets its data The data property’s setter calls notifyDataSetChanged() notifyDataSetChanged() redraws the entire list Tell the recycler view what needs to change DiffUtil works out differences between lists Here’s what we’re going to do We need to implement DiffUtil.ItemCallback Create TaskDiffItemCallback.kt A ListAdapter accepts a DiffUtil.ItemCallback argument We can simplify the rest of TaskItemAdapter’s code The updated code for TaskItemAdapter.kt Populate the ListAdapter’s list… …using submitList() The updated code for TasksFragment.kt What happens when the code runs Test Drive BE the ListAdapter Recycler views can use data binding How we’ll implement data binding Add a data binding variable to task_item.xml The layout gets inflated in the adapter’s view holder code Use the binding class to inflate the layout Set the layout’s data binding variable to a Task The full code for TaskItemAdapter.kt Use data binding to set the layout’s views The full code for task_item.xml What happens when the code runs Test Drive Adapter Magnets Adapter Magnets Solution BE the ListAdapter Solution Your Android Toolbox 17. Recycler View Navigation: Pick a Card Recycler views can be used for navigation How the Tasks app is currently structured We’re going to make the recycler view navigate to a new fragment Here’s what we’re going to do Make each item clickable Where should we create the toast? We’ll make TasksFragment pass the toast code in a lambda How the code will work The full code for TaskItemAdapter.kt We’ll pass a lambda to TaskItemAdapter The full code for TasksFragment.kt What happens when the code runs Test Drive Adapter Magnets Adapter Magnets Solution We want to use the recycler view to navigate to a new fragment Update the project build.gradle file… …then update the app build.gradle file Create EditTaskFragment… …and create a navigation graph Update the navigation graph Add a NavHostFragment to MainActivity’s layout Make TasksFragment navigate to EditTaskFragment Add a new property to TasksViewModel Add methods to update the new property The full code for TasksViewModel.kt Make TasksFragment navigate to EditTaskFragment Call onTaskClicked() when the user clicks a task Navigate to EditTaskFragment when navigateToTask gets updated The full code for TasksFragment.kt Make EditTaskFragment display the task ID We also need to update EditTaskFragment.kt The full code for EditTaskFragment.kt What happens when the code runs Test Drive We want to use EditTaskFragment to update task records Use TaskDao to interact with database records We’ll create a view model to access TaskDao’s methods Create EditTaskViewModel The view model needs to get a task record… …and include methods to update and delete the task EditTaskViewModel will tell EditTaskFragment when to navigate The full code for EditTaskViewModel.kt EditTaskViewModel needs a view model factory Create EditTaskViewModelFactory fragment_edit_task.xml needs to display the task We need to update EditTaskFragment.kt too The full code for EditTaskFragment.kt What happens when the code runs Test Drive Your Android Toolbox 18. Jetpack Compose: Compose Yourself UI components don’t have to be Views We’re going to build a Compose app Here’s what we’re going to do Create a new Compose project Configure the project Compose projects have no layout files What Compose activity code looks like Compose activities extend ComponentActivity Use a Text composable to display text Use composables in composable functions Call the Hello composable from setContent() Most UIs have multiple composables You can arrange composables using Row or Column The full code for MainActivity.kt Test Drive You can preview composable functions Add MainActivityPreview to MainActivity.kt Preview composables with the Design or Split option Pool Puzzle Pool Puzzle Solution Let’s make the app convert temperatures Add a MainActivityContent composable function Display the header image… …with an Image composable Add an Image to MainActivity.kt Let’s display the temperature text Test Drive Use a Button composable to add a button Let’s write a ConvertButton composable function We need to pass a lambda to ConvertButton We need to change the value of TemperatureText’s argument Use remember to store celsius in memory The full code for MainActivity.kt What happens when the app runs Test Drive Compose Magnets Compose Magnets Solution Let the user enter a temperature We’ll use a TextField composable Add a TextField to a composable function Call the function in MainActivityContent The full code for MainActivity.kt What happens when the app runs Test Drive We’ll tweak the app’s appearance Add padding to the Column composable You can center composables in Columns or Rows Center all of a Column’s content Center the content of a single Row Applying themes: revisited How to apply a theme to composables Android Studio includes extra theme code How to apply the theme The full code for MainActivity.kt Test Drive BE Compose BE Compose Solution Your Android Toolbox 19. Integrating Compose with views: Perfect Harmony You can add composables to View-based UIs The Guessing Game app revisited The Guessing Game app structure Here’s what we’re going to do Update the project build.gradle file… …and update the app build.gradle file, too We’ll replace ResultFragment’s views with composables A ComposeView lets you add composables to a layout We’ll add a ComposeView to fragment_result.xml Add composables using Kotlin code Add a composable function for the fragment’s content Reproduce the Start New Game button Reproduce ResultFragment’s TextView The updated code for ResultFragment.kt Test Drive We need to remove ResultFragment’s views… …and update ResultFragment.kt onCreateView() returns the UI’s root view Return a ComposeView for Compose UIs The full code for ResultFragment.kt We can delete fragment_result.xml What happens when the app runs Test Drive Pool Puzzle Next we’ll make GameFragment use composables too We’ll add a ComposeView to fragment_game.xml Add a composable function for GameFragment’s content Reproduce the Finish Game button Reproduce the EditText with a TextField Reproduce the Guess button The updated code for GameFragment.kt Test Drive We’ll display the incorrect guesses in a Text composable Respond to LiveData using observeAsState() Create an IncorrectGuessesText composable function Run IncorrectGuessesText from GameFragmentContent Compose Magnets Compose Magnets Solution The updated code for GameFragment.kt Test Drive Remove views from GameFragment.kt Delete fragment_game.xml We can also switch off data binding Test Drive Pool Puzzle Solution Your Android Toolbox Leaving town It’s been great having you here in Androidville A. Leftovers: The Top Ten Things (we didn’t cover) 1. Sharing data with other apps Sharing data with Android’s intent resolver Sharing data with the Android Sharesheet 2. WorkManager Use WorkManager to schedule deferrable tasks 3. Dialogs and notifications Use dialogs to prompt the user for a decision Notifications appear outside the app’s UI 4. Automated testing Unit tests Instrumented tests An instrumented test example 5. Supporting different screen sizes Provide alternate layouts Use a SlidingPaneLayout 6. More Compose features The Compose ViewModel library Compose constraint layout library The Compose Navigation component 7. Retrofit 8. Android Game Development Kit 9. CameraX 10. Publishing your app Preparing your app for release Releasing your app Index
Donate to keep this site alive
How to download source code?
1. Go to: https://www.oreilly.com/
2. Search the book title: Head First Android Development: A Learner’s Guide to Building Android Apps with Kotlin, 3rd Edition
, sometime you may not get the results, please search the main title
3. Click the book title in the search results
3. Publisher resources
section, click Download Example Code
.
1. Disable the AdBlock plugin. Otherwise, you may not get any links.
2. Solve the CAPTCHA.
3. Click download link.
4. Lead to download server to download.