Table of contents : Title Page Copyright About the Authors Table of Contents Introduction Who is this book for? We know what you’re thinking Metacognition: thinking about thinking Here’s what WE did Here’s what YOU c an do to bendyour brain into submission Read me The technical review team Acknowledgments O’Reilly Online Learning Chapter 1 Welcome to Androidville Activities and layouts form the backbone of your app Here’s what we’re going to do Android Studio Install Android Studio Let’s build a basic app How to build the app You’ve created your first Android project Dissecting your new project Introducing the key files in your project Edit code with the Android Studio editors The story so far How to run the app on a physical device How to run the app on a virtual device Create an Android Virtual Device Compile, package, deploy, run What just happened? Let’s refine the app What’s in the layout? activity_main.xml has two elements Update the text displayed in the layout What the code does Your Android Toolbox Chapter 2 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 activity_main.xml has a new button A closer look at the layout code Let’s update the layout XML The XML changes are reflected in the design editor There are warnings in the layout… Put text in a String resource file Extract the String resource activity_main.xml uses the String resource Add and use a new String resource Add values to the spinner Add the string-array to strings.xml The full code for activity_main.xml We need to make the app interactive What the MainActivity code looks like A button can listen for on-click events… Get a reference to the button… Pass a lambda to the setOnClickListener method How to edit a text view’s text The updated code for MainActivity.kt What happens when you run the code Add the getBeers() method The full code for MainActivity.kt What happens when you run the code Your Android Toolbox Chapter 3 It all starts with a layout Android has different types of layout Let’s build a linear layout 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 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 Your activity code tells Android which layout it uses Layout inflation: an example A frame layout stacks its views Add an image to your project A frame layout stacks views in the order they appear in the layout XML All layouts are a type of ViewGroup… A scroll view inserts a vertical scrollbar How to add a scroll view Your Android Toolbox Chapter 4 Nested layouts revisited Nesting layouts comes at a price Introducing the constraint layout Constraint layouts are part of Android Jetpack Here’s what we’re going to do Use Gradle to include Jetpack libraries Let’s add a constraint layout to activity_main.xml Add a button to the blueprint Position views using constraints 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 Changes to the blueprint appear in the XML Views can have bias You can change a view’s size Most layouts need multiple views 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 Add a horizontal barrier Constrain a button under the barrier The full code for activity_main.xml Use a chain to control a linear group of views The chain will use three buttons Create the horizontal chain There are different styles of chain A flow is like a multi-line chain How to add a flow You can control the flow’s appearance The full code for activity_main.xml Your Android Toolbox Chapter 5 How do activities really work? Create a new project The full code for activity_main.xml The activity code controls the stopwatch The full code for MainActivity.kt MainActivity.kt continued What happens when you run the app The story continues 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 Save the state using onSaveInstanceState() The updated MainActivity.kt code What happens when you run the app There’s more to an activity’s life than create and destroy The visible lifecycle We need to implement two more lifecycle methods Restart the stopwatch when the app becomes visible The updated MainActivity.kt code What happens when you run the app 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 Your handy guide to the activity lifecycle methods Your Android Toolbox Chapter 6 Most apps need more than one screen Each screen is a fragment Navigate between screens using the Navigation component Here’s what we’re going to do Create a new project Add WelcomeFragment to the project What fragment code looks like The fragment’s onCreateView() method Fragment layout code looks like activity layout code You display a fragment in a FragmentContainerView Update the activity_main.xml code What the code does Create MessageFragment Update MessageFragment’s layout Update MessageFragment.kt Use the Navigation component to navigate between fragments Create a navigation graph Add fragments to the navigation graph Connect fragments using an action Navigation graphs are XML resources Add a navigation host to the layout using a FragmentContainerView Add a NavHostFragment to activity_main.xml Add an OnClickListener to the button Get a navigation controller The full code for WelcomeFragment.kt What happens when the app runs Your Android Toolbox Chapter 7 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… Update EncryptFragment.kt Add EncryptFragment to the navigation graph The updated nav_graph.xml code MessageFragment needs to navigate to EncryptFragment Add Safe Args to the build.gradle files EncryptFragment needs to accept a String argument The updated nav_graph.xml code MessageFragment needs to pass a message to EncryptFragment Safe Args generates Directions classes Update the MessageFragment.kt code EncryptFragment needs to get the argument's value The full code for EncryptFragment.kt What happens when the app runs What if the user wants to go back? We could change the back behavior Welcome to the back stack Use the navigation graph to pop fragments off the back stack The updated nav_graph.xml code Your Android Toolbox Chapter 8 Different apps, different structures Android includes navigation UI components How the CatChat app will work Here’s what we’re going to do Create a new project The CatChat app will use a Material theme Apply a theme in AndroidManifest.xml Define styles in style resource files Styles can override theme colors Replace the default app bar with a toolbar A toolbar is a type of View Add the toolbar to activity_main.xml Set the toolbar as MainActivity's app bar Let’s use the toolbar to navigate Create InboxFragment Create HelpFragment We’ll use the Navigation component to navigate to HelpFragment 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 Most types of UI navigation work with the Navigation component 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 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… Highlight the selected item with groups The full code for menu_main.xml Create the navigation drawer’s header How to create a navigation drawer The full code for activity_main.xml Configure the toolbar’s drawer icon… The full code for MainActivity.kt Your Android Toolbox Chapter 9 Material is used throughout Androidville The Bits and Pizzas app Here’s what we’ll do Create the Bits and Pizzas project 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? 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 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 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 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 Let’s make the FAB respond to clicks Add an OnClickListener to the FAB A toast is a simple pop-up message Display the pizza order in a snackbar The snackbar code for the pizza order The full code for OrderFragment.kt Your Android Toolbox Chapter 10 Behind the scenes of findViewById() There’s a downside to findViewById() View binding to the rescue Here’s how we’ll use view binding The Stopwatch app revisited Enable view binding in the app build.gradle file How to add view binding to an activity Use the binding property to interact with views The full code for MainActivity.kt What the code does Fragments can use view binding too (but the code’s a little different) Enable view binding for Bits and Pizzas Fragment view binding code is a little different Fragments can access views from onCreateView() to onDestroyView() What fragment view binding code looks like _binding refers to the binding object… The full code for OrderFragment.kt Your Android Toolbox Chapter 11 Configuration changes revisited Introducing the view model What the guessing game will do How the app will be structured Here’s what we’re going to do Update the project build.gradle file… The Guessing Game app has two fragments How navigation should work Update the navigation graph Display the current fragment in MainActivity’s layout Update GameFragment’s layout The GameFragment.kt code Update ResultFragment’s layout The ResultFragment.kt code What happens when the app runs 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… The full code for GameViewModel.kt Create a GameViewModel object The updated code for GameFragment.kt What happens when the app runs We’ve added a view model for GameFragment ResultViewModel needs to hold the result 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 Your Android Toolbox Chapter 12 The Guessing Game app revisited The fragments decide when to update views Here’s what we’re going to do GameViewModel and GameFragment need to use live data Live data objects use a value property 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 Fragments can update GameViewModel’s proper The full code for GameViewModel.kt What happens when the app runs GameFragment still includes game logic The full code for GameViewModel.kt Make GameFragment observe the new property What happens when the app runs Your Android Toolbox Chapter 13 Back to the Guessing Game app The fragments update the views in their layouts Here’s what we’re going to do Enable data binding in the app build.gradle file ResultFragment updates the text in its layout 1. Add and 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 GameFragment can use data binding too Add and elements to fragment_game.xml Use the data binding variable to set the layout’s text String resources revisited The layout can pass parameters to String resources The full code for fragment_game.xml We need to set the gameViewModel variable The full code for GameFragment.kt What happens when the app runs 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 We can switch off view binding Your Android Toolbox Chapter 14 Most apps need to store data How the app will be structured Room is a database library that sits on top of SQLite Here’s what we’re going to do Add a variable to the project build.gradle file… Create TasksFragment Update fragment_tasks.xml Display TasksFragment in MainActivity’s layout How Room databases are created We’ll store tasks data in a table Specify a table name with @Entity The full code for Task.kt Use an interface to specify data operations Use @Insert to insert a record Use @Delete to delete a record The full code for TaskDao.kt Create a TaskDatabase abstract class Add properties for any DAO interfaces The full code for TaskDatabase.kt MVVM revisited Create TasksViewModel Database operations can run in slooooow-moooo 1. Mark TaskDao’s methods with suspend 2. Launch the insert() method in the background TasksViewModel needs a view model factory TasksViewModelFactory needs a TaskDao The updated code for TasksFragment.kt TasksFragment can use data binding We’ll use data binding to insert a record The full fragment_tasks.xml code The full TasksFragment.kt code What happens when the code runs TasksFragment needs to display records Use getAll() to get all tasks from the database A LiveData is a more complex type Let’s update the TasksViewModel co We’ll bind the tasksString property to the layout’s text view The full TasksFragment.kt code What happens when the code runs Your Android Toolbox Chapter 15 What the Tasks app currently looks like We can turn the list into a recycler view Why use a recycler view? Here’s what we’re going to do Tell the recycler view how to display each item The adapter adds data to the recycler view Tell the adapter what data it should work with 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 The full code for fragment_tasks.xml The updated code for TasksFragment.kt We’ve added a recycler view to TasksFragment’s layout Update the TasksViewModel.kt code TasksFragment needs to update TaskItemAdapter’s data property The full code for TasksFragment.kt What happens when the code runs Recycler views are very flexible Recycler view 2.0 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 cod The full code for TaskItemAdapter.kt What the recycler view looks like so far The layout manager gallery Update fragment_tasks.xml to arrange items in a grid What happens when the code runs Your Android Toolbox Chapter 16 The recycler view displays task data correctly The Tasks app revisited How the recycler view gets its data The data property’s setter calls notifyDataSetChanged() Tell the recycler view what needs to change Here’s what we’re going to do We need to implement DiffUtil.ItemCallback A ListAdapter accepts a DiffUtil.ItemCallback argument The updated code for TaskItemAdapter.kt Populate the ListAdapter’s l The updated code for TasksFragment.kt What happens when the code runs Recycler views can use 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 The full code for TaskItemAdapter.kt The full code for task_item.xml What happens when the code runs Your Android Toolbox Chapter 17 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? 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 We want to use the recycler view to navigate to a new fragment Update the project build.gradle file Create EditTaskFragment Update the navigation graph Add a NavHostFragment to MainActivity’s layout Make TasksFragment navigate to EditTaskFragment Add a new property to TasksViewModel The full code for TasksViewModel.kt Make TasksFragment navigate to EditTaskFragment The full code for TasksFragment.kt Make EditTaskFragment display the task ID The full code for EditTaskFragment.kt What happens when the code runs We want to use EditTaskFragment to update task records se TaskDao to interact with database records Create EditTaskViewModel EditTaskViewModel will tell EditTaskFragment when to navigate The full code for EditTaskViewModel.kt EditTaskViewModel needs a view model factory fragment_edit_task.xml needs to display the task The full code for EditTaskFragment.kt What happens when the code runs Your Android Toolbox Chapter 18 UI components don't have to be Views 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 Use a Text composable to display text Use composables in composable functions Most UIs have multiple composables The full code for MainActivity.kt You can preview composable functions Preview composables with the Design or Split option Let’s make the app convert temperatures Add a MainActivityContent composable function Display the header image Add an Image to MainActivity.kt Let’s display the temperature text Use a Button composable to add a button We need to pass a lambda to ConvertButton We need to change the value of TemperatureText’s argument The full code for MainActivity.kt What happens when the app runs Let the user enter a temperature Add a TextField to a composable function The full code for MainActivity.kt What happens when the app runs We’ll tweak the app’s appearance Add padding to the Column composable You can center composables in Columns or Rows Applying themes: revisited Android Studio includes extra theme code The full code for MainActivity.kt Your Android Toolbox Chapter 19 You can add composables to View-based UIs The Guessing Game app structure Here’s what we’re going to do Update the project build.gradle file We’ll replace ResultFragment’s views with composables A ComposeView lets you add composables to a layout 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 We need to remove ResultFragment’s views onCreateView() returns the UI’s root view The full code for ResultFragment.kt What happens when the app runs Next we’ll make GameFragment use composables too We’ll add a ComposeView to fragment_game.xml Add a composable function forGameFragment’s content Reproduce the Finish Game button Reproduce the EditText with a TextField Reproduce the Guess button The updated code for GameFragment.kt We’ll display the incorrect guesses in a Text composable Create an IncorrectGuessesText composable function The updated code for GameFragment.kt Remove views from GameFragment.kt Delete fragment_game.xml Your Android Toolbox Leaving town Appendix 1. Sharing data with other apps 2. WorkManager 3. Dialogs and notifications 4. Automated testing 5. Supporting different screen sizes 6. More Compose features 7. Retrofit 8. Android Game Development Kit 9. CameraX 10. Publishing your app Index