How to use this book: Intro
Your brain on Android. Here you are trying to learn something, while here your brain is, doing you a favor by making sure the learning doesnât stick. Your brainâs thinking, âBetter leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.â So how do you trick your brain into thinking that your life depends on knowing how to develop Android apps?
âWho is this book for?â
âWe know what youâre thinkingâ
âWe know what your brain is thinkingâ
âMetacognition: thinking about thinkingâ
âHereâs what WE didâ
âRead meâ
âThe truly awesome technical review teamâ
âAcknowledgmentsâ
Chapter 1
Android is the worldâs most popular mobile operating system. And there are billions of Android users worldwide, all waiting to download your next great idea. In this chapter, youâll find out how to start turning your ideas into reality by building a basic Android app, and updating it. Youâll learn how to run it on physical and virtual devices. Along the way, youâll meet two of the core components of all Android apps: activities and layouts.
âWelcome to Androidvilleâ
âActivities and layouts form the backbone of your appâ
âHereâs what weâre going to doâ
âAndroid Studio: your development environmentâ
âInstall Android Studioâ
âLetâs build a basic appâ
âHow to build the appâ
âAndroid Versions Up Close â
â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 (AVD)â
â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
Most apps need to respond to the user in some way. And in this chapter, youâll see how you can make your apps more interactive. Youâll discover how to add an OnClickListener to your activity code so that your app can listen to what the userâs doing, and make an appropriate response. Youâll find out more about how to design layouts, and youâll learn how each UI component you add to your layout is derived from a common View ancestor. Along the way, youâll discover why String resources are so important for flexible, well-designed apps.
âLetâs build a Beer Adviser appâ
âCreate the projectâ
âA closer look at the design editorâ
âAdd a button using the design editorâ
â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â
âAdd and use a new String resourceâ
âString Resources Up Close â
âAdd values to the spinnerâ
âAdd the string-array to strings.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â
âYour Android Toolboxâ
Chapter 3
Weâve only scratched the surface of using layouts. So far, youâve seen how to arrange views in a simple linear layout, but thereâs so much more that layouts can do. In this chapter weâll go a little deeper and show you how layouts really work. Youâll learn how to fine-tune your linear layouts. Youâll discover how to use frame layouts and scroll views. And by the end of the chapter, youâll learn that even though they might look a little different, all layoutsâand the views you add to themâhave more in common than you might think.
âIt all starts with a layoutâ
âAndroid has different types of layoutâ
âHow to define a linear layoutâ
âOrientation can be vertical or horizontalâ
âAnatomy of AndroidManifest.xml â
â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â
âValues you can use with the android:gravity attributeâ
âThe story so farâ
âMore values you can use with the android:layout-gravity attributeâ
âUse margins to add space between viewsâ
â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â
âDrawable Resources Up Close â
â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â
âYour Android Toolboxâ
Chapter 4
You donât build a house without a blueprint. And some layouts use blueprints to make sure they look exactly the way you want. In this chapter, weâll introduce you to Androidâs constraint layout: a flexible way of designing more complex UIs. Youâll discover how constraints and bias let you position and size your views, irrespective of screen size and orientation. Youâll find out how to keep views in their place with guidelines and barriers. Finally, youâll learn how to pack or spread views with chains and flows.
âNested layouts revisitedâ
âIntroducing the constraint layoutâ
âConstraint layouts are part of Android Jetpackâ
â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â
â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â
âAlign views using guidelinesâ
âGuidelines have a fixed positionâ
âCreate a movable barrierâ
âAdd a horizontal barrierâ
âConstrain a button under the barrierâ
âUse a chain to control a linear group of viewsâ
â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â
âYour Android Toolboxâ
Chapter 5
Activities form the foundation of every Android app. So far youâve seen how to create an activity, and use it to interact with the user. But if you donât know about the activity lifecycle, some of its behavior might take you by surprise. In this chapter, youâll learn what happens when an activity is created and destroyed, and how this can lead to unexpected consequences. Youâll find out how to control its behavior when itâs made visible, or hidden. Youâll even discover ways of saving and restoring your activityâs state, just when you need it.
â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â
âWhat happens when you run the appâ
â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â
â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 require more than one screen. So far, weâve just looked at how to create single-screen apps, which is fine for simple applications. But what if you have more complex requirements? In this chapter, youâll learn how to use fragments and the Navigation component to build multi-screen apps. Youâll learn how fragments are like subactivities with their own methods. Youâll find out how to design effective navigation graphs. Finally, youâll meet the navigation host and navigation controller, and learn how they help you navigate from place to place.
âMost apps need more than one screenâ
âEach screen is a fragmentâ
âNavigate between screens using the Navigation componentâ
â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â
âUse the Navigation component to navigate between fragmentsâ
âUse Gradle to add the Navigation component to your projectâ
â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
Sometimes fragments need extra information to work properly. If a fragment shows details of a contact, for example, it needs to know which contact to display. But what if this information comes from another fragment? In this chapter, youâll build on your navigation know-how by learning how to pass data between fragments. Youâll find out how to add arguments to navigation destinations so they can receive the information they need. Youâll meet the Safe Args plug-in, and learn how to use it to write type-safe code. Finally, youâll discover how to manipulate the back stack, and take control of back button behavior.
âThe Secret Message app navigates between fragmentsâ
âMessageFragment needs to pass the message to a new fragmentâ
âCreate EncryptFragmentâ¦â
âAdd EncryptFragment to the navigation graphâ
âMessageFragment needs to navigate to EncryptFragmentâ
âAdd Safe Args to the build.gradle filesâ
âEncryptFragment needs to accept a String argumentâ
â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?â
âWelcome to the back stackâ
âUse the navigation graph to pop fragments off the back stackâ
âYour Android Toolboxâ
Chapter 8
Most apps need to be able to navigate between destinations. And with the Android the Navigation component, building this UI became much simpler. Here, youâll learn how to use some of Androidâs navigation UI components so that your users can navigate your app more easily. Youâll see how to use themes, and replace your appâs default app bar with a toolbar. Youâll learn how to add menu items you can use for navigation. Youâll discover how to implement bottom bar navigation. Finally, youâll create a swish navigation drawer: a panel that slides out from the side of your activity.
âDifferent apps, different structuresâ
âAndroid includes navigation UI componentsâ
âHow the CatChat app will workâ
âApply a theme in AndroidManifest.xmlâ
âDefine styles in style resource filesâ
âReplace the default app bar with a toolbarâ
âCreate InboxFragmentâ
âSpecify items in the toolbar with a menu resource fileâ
âonCreateOptionsMenu() adds menu items to the toolbarâ
âRespond to menu item clicks with onOptionsItemSelected()â
âConfigure the toolbar using an AppBarConfigurationâ
âWhat happens when the app runsâ
âMost types of UI navigation work with the Navigation componentâ
âCreate SentItemsFragmentâ
âThe bottom navigation bar needs a new menu resource fileâ
âLink the bottom navigation bar to the navigation controllerâ
âA navigation drawer lets you display many navigation itemsâ
âAdd the support sectionâ¦â
âHighlight the selected item with groupsâ
âCreate the navigation drawerâs headerâ
âHow to create a navigation drawerâ
âConfigure the toolbarâs drawer iconâ¦â
âYour Android Toolboxâ
Chapter 9
Most apps need a slick UI that responds to the user. Youâve so far learned how to use views such as text views, buttons, and spinners, and applied Material themes to make sweeping changes to your appâs look and feel. But thereâs so much more you can do. Here, youâll learn how to make your UI more responsive with the coordinator layout. Youâll create toolbars that can collapse or scroll on a whim. Youâll discover exciting new views such as checkboxes, radio buttons, chips, and floating action buttons. Finally, youâll find out how to display friendly pop-up messages using toasts and snackbars.
âMaterial is used throughout Androidvilleâ
âThe Bits and Pizzas appâ
âCreate OrderFragmentâ
âReplace the default app bar with a toolbarâ
âFragments donât have a setSupportActionBar() methodâ
âThe coordinator layout coordinates animations between viewsâ
âThe app bar layout enables toolbar animationâ
âTell the toolbar how to respond to scroll eventsâ
âHow to create a plain collapsing toolbarâ
âHow to add an image to a collapsing toolbarâ
âWe need to build OrderFragmentâs main contentâ
âChoose a pizza type using a radio 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â
â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
Itâs time to wave farewell to findViewById(). As youâve probably noticed by now, the more views you have and the more interactive your apps become, the more calls you need to make to findViewById(). And if youâre getting tired of typing the code for this method every time you want to work with a view, youâre not alone. In this chapter, youâll discover how to make findViewById() a thing of the past by implementing view binding. Youâll find out how to apply this technique to both activity and fragment code, and youâll learn why this approach is a safer, more efficient way of accessing your layoutâs views.
â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()â
âFragment Lifecycle Methods Up Close â
âWhat fragment view binding code looks likeâ
â_binding refers to the binding objectâ¦â
âThe full code for OrderFragment.ktâ
âYour Android Toolboxâ
Chapter 11
As apps grow more complex, fragments have more to juggle. And if youâre not careful, this can lead to bloated code that tries to do everything. Business logic, navigation, controlling the UI, dealing with configuration changesâ¦you name it, itâs in there. In this chapter, youâll learn how to deal with this kind of situation using view models. Youâll discover how they simplify your activity and fragment code. Youâll find out how they survive configuration changes, keeping your appâs state safe and sound. Finally, weâll show you how to build a view model factory, and when this might be needed.
âConfiguration changes revisitedâ
âIntroducing the view modelâ
âWhat the guessing game will doâ
âHow the app will be structuredâ
âUpdate the project build.gradle fileâ¦â
âThe Guessing Game app has two fragmentsâ
âHow navigation should workâ
âUpdate the navigation graphâ
â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â¦â
âCreate a GameViewModel objectâ
âWhat happens when the app runsâ
â View Models Up Closeâ
â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â
âWhat happens when the app runsâ
âYour Android Toolboxâ
Chapter 12
Your code often needs to react to property value changes. If a view model property changes value, for example, the fragment might need to respond by updating its views or navigating elsewhere. But how does a fragment get to hear when a propertyâs been updated? Here, weâll introduce you to live data: a way of telling interested parties when somethingâs changed. Youâll learn all about MutableLiveData, and how to make your fragment observe properties of this type. Youâll discover how the LiveData type helps maintain your appâs integrity.
â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 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 propertiesâ
â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
Layouts can do more than control your appâs appearance. All of the layouts youâve written so far have been told how they should behave by activity or fragment code. But just imagine if the layouts could think for themselves, and make their own decisions. In this chapter, weâll introduce you to data binding: a way of boosting your layoutâs IQ. Youâll find out how to make views get values directly from the view model. Youâll use listener binding to make buttons call their methods. Youâll even discover how one simple line of code lets views respond to live data updates.
âBack to the Guessing Game appâ
âThe fragments update the views in their layoutsâ
âEnable data binding in the app build.gradle fileâ
âResultFragment updates the text in its layoutâ
â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â
âWhat happens when the app runsâ
â <layout> Up Closeâ
â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â
âString resources revisitedâ
âThe layout can pass parameters to String resourcesâ
âWe need to set the gameViewModel variableâ
â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â
âWhat happens when the app runsâ
âFireside Chatsâ
âWe can switch off view bindingâ
âYour Android Toolboxâ
Chapter 14
Most apps need data that persists. But if you donât take steps to store this data somewhere, it will be lost forever as soon as the app is closed down. You usually keep data safe in Androidville by storing it in a database, so in this chapter, weâll introduce you to the Room persistence library. Youâll learn how to build databases, create tables, and define data access methods using annotated classes and interfaces. Youâll find out how to use coroutines to run database code in the background. And along the way, youâll discover how to transform your live data as soon as it changes with a little help from Transformations.map().
âMost apps need to store dataâ
âRoom is a database library that sits on top of SQLiteâ
âCreate TasksFragmentâ
âHow Room databases are createdâ
âWeâll store tasks data in a tableâ
âSpecify a table name with @Entityâ
âUse an interface to specify data operationsâ
âUse @Insert to insert a recordâ
âUse @Delete to delete a recordâ
âCreate a TaskDatabase abstract classâ
âAdd properties for any DAO interfacesâ
âMVVM revisitedâ
â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â
âWeâll use data binding to insert a recordâ
âWhat happens when the code runsâ
âTasksFragment needs to display recordsâ
âUse getAll() to get all tasks from the databaseâ
âA LiveData<List<Task>> is a more complex typeâ
âLetâs update the TasksViewModel codeâ
âWeâll bind the tasksString property to the layoutâs text viewâ
âWhat happens when the code runsâ
âYour Android Toolboxâ
Chapter 15
Lists of data are a key part of most apps. And in this chapter, weâll show you how to create one using a recycler view: a super-flexible way of building a scrollable list. Youâll learn how to create flexible layouts for your list, including text views, checkboxes, and more. Youâll find out how to create adapters that squish your data into the recycler view in whatever way you choose. Youâll discover how to use card views to give your data a 3D material look. Finally, weâll show you how layout managers can completely change the look of your list with just one or two lines of code.
âWhat the Tasks app currently looks likeâ
âWe can turn the list into a recycler viewâ
âTell the recycler view how to display each itemâ¦â
âThe adapter adds data to the recycler viewâ
âDefine the adapterâs view holderâ
âOverride the onCreateViewHolder() methodâ
âAdd data to the layoutâs viewâ
âWe need to display the recycler viewâ
âWeâve added a recycler view to TasksFragmentâs layoutâ
âTasksFragment needs to update TaskItemAdapterâs data propertyâ
âWhat happens when the code runsâ
âRecycler views are very flexibleâ
â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â
â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
Your app needs to run as smoothly and efficiently as possible. But if youâre not careful, large or complex data sets can cause your recycler view to glitch. In this chapter, weâll introduce you to DiffUtil: a utility class that adds extra smarts to your recycler view. Youâll find out how to use it to make efficient updates to your recycler view. Youâll discover how ListAdapters make using DiffUtil a breeze. And along the way, youâll learn how to get rid of findViewById() for good by implementing data binding in your recycler view code.
â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 listâ¦â
â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
Some apps rely on the user selecting an item from a list. And in this chapter, youâll learn how to make recycler views a core part of your app design by making their items clickable. Youâll discover how to implement recycler view navigation by making the app navigate to a new screen each time the user clicks on a record. Youâll find out how to show the user extra information about their chosen record, and update it in the database.
âRecycler views can be used for navigationâ
âMake each item clickableâ
âWhere should we create the toast?â
âWeâll pass a lambda to TaskItemAdapterâ
âWhat happens when the code runsâ
âWe want to use the recycler view to navigate to a new fragmentâ
âCreate EditTaskFragmentâ¦â
âUpdate the navigation graphâ
âMake TasksFragment navigate to EditTaskFragmentâ
âMake EditTaskFragment display the task IDâ
âWhat happens when the code runsâ
âWe want to use EditTaskFragment to update task recordsâ
âUse TaskDao to interact with database recordsâ
âCreate EditTaskViewModelâ
âEditTaskViewModel will tell EditTaskFragment when to navigateâ
âEditTaskViewModel needs a view model factoryâ
âfragment_edit_task.xml needs to display the taskâ
âWhat happens when the code runsâ
âYour Android Toolboxâ
Chapter 18
All the UIs youâve built so far have used views and layout files. But with Jetpack Compose, thatâs not the only option. In this chapter, weâre going to take a road trip to Composeville, and find out how to build UIs using Compose components called composables instead of views. Youâll learn how to use built-in composables such as Text, Image, TextField, and Button. Youâll discover how to arrange them in Rows and Columns, and style them using themes. Youâll write and preview your own composable functions. Youâll even find out how to manage a composableâs state using MutableState objects.
âUI components donât have to be Viewsâ
âCreate a new Compose 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â
âPreview composables with the Design or Split optionâ
âLetâs make the app convert temperaturesâ
âAdd a MainActivityContent composable functionâ
â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â
â Composition Up Closeâ
âWe need to change the value of TemperatureTextâs argumentâ
âWhat happens when the app runsâ
âAdd a TextField to a composable functionâ
âWhat happens when the app runsâ
â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 get the best results when things work together. So far, youâve learned how to build a UI using views or composables. But what if you want to use both? In this chapter, youâll find out how to get the best of both worlds by adding composables to a View-based UI. Youâll discover techniques for making composables work with view models. Youâll even find out how to make them respond to LiveData updates. By the end of the chapter, youâll have all the tools you need to use composables with views, or even migrate to a pure Compose UI.
âYou can add composables to View-based UIsâ
âThe Guessing Game app structureâ
â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â
â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 for GameFragmentâs contentâ
âReproduce the Finish Game buttonâ
âReproduce the EditText with a TextFieldâ
âReproduce the Guess buttonâ
âWeâll display the incorrect guesses in a Text composableâ
âCreate an IncorrectGuessesText composable functionâ
âYour Android Toolboxâ
Appendix A
Even after all that, thereâs still a little more. There are just a few more things we think you need to know. We wouldnât feel right about ignoring them, and we really wanted to give you a book youâd be able to lift without extensive training at the local gym. Before you put down the book, read through these tidbits.
â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â