Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.2 Development Essentials - Kotlin Edition

You're reading from  Android Studio 4.2 Development Essentials - Kotlin Edition

Product type Book
Published in Aug 2021
Publisher Packt
ISBN-13 9781803231549
Pages 804 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (94) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to Using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures Using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Primary/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. An Introduction to Kotlin Coroutines 64. An Android Kotlin Coroutines Tutorial 65. An Overview of Android Services 66. Implementing an Android Started Service – A Worked Example 67. Android Local Bound Services – A Worked Example 68. Android Remote Bound Services – A Worked Example 69. An Android Notifications Tutorial 70. An Android Direct Reply Notification Tutorial 71. Foldable Devices and Multi-Window Support 72. An Overview of Android SQLite Databases 73. The Android Room Persistence Library 74. An Android TableLayout and TableRow Tutorial 75. An Android Room Database and Repository Tutorial 76. Accessing Cloud Storage using the Android Storage Access Framework 77. An Android Storage Access Framework Example 78. Video Playback on Android using the VideoView and MediaController Classes 79. Android Picture-in-Picture Mode 80. An Android Picture-in-Picture Tutorial 81. Making Runtime Permission Requests in Android 82. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 83. Printing with the Android Printing Framework 84. An Android HTML and Web Content Printing Example 85. A Guide to Android Custom Document Printing 86. An Introduction to Android App Links 87. An Android Studio App Links Tutorial 88. A Guide to the Android Studio Profiler 89. An Android Biometric Authentication Tutorial 90. Creating, Testing and Uploading an Android App Bundle 91. An Overview of Android Dynamic Feature Modules 92. An Android Studio Dynamic Feature Tutorial 93. An Overview of Gradle in Android Studio Index

38. Using Fragments in Android Studio - An Example

As outlined in the previous chapter, fragments provide a convenient mechanism for creating reusable modules of application functionality consisting of both sections of a user interface and the corresponding behavior. Once created, fragments can be embedded within activities.

Having explored the overall theory of fragments in the previous chapter, the objective of this chapter is to create an example Android application using Android Studio designed to demonstrate the actual steps involved in both creating and using fragments, and also implementing communication between one fragment and another within an activity.

38.1 About the Example Fragment Application

The application created in this chapter will consist of a single activity and two fragments. The user interface for the first fragment will contain a toolbar of sorts consisting of an EditText view, a SeekBar and a Button, all contained within a ConstraintLayout view. The second fragment will consist solely of a TextView object, also contained within a ConstraintLayout view.

The two fragments will be embedded within the main activity of the application and communication implemented such that when the button in the first fragment is pressed, the text entered into the EditText view will appear on the TextView of the second fragment using a font size dictated by the position of the SeekBar in the first fragment.

Since this application is intended to work on earlier versions of Android, it will also be necessary to make use of the appropriate Android support library.

38.2 Creating the Example Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter FragmentExample into the Name field and specify com.ebookfrenzy.fragmentexample as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Kotlin. Using the steps outlined in section 18.8 Migrating a Project to View Binding, modify the project to use view binding.

Return to the Gradle Scripts -> build.gradle (Module: FragmentExample) file and add the following directive to the dependencies section (keeping in mind that a more recent version of the library may now be available):

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'

38.3 Creating the First Fragment Layout

The next step is to create the user interface for the first fragment that will be used within our activity.

This user interface will consist of an XML layout file and a fragment class. While these could be added manually, it is quicker to ask Android Studio to create them for us. Within the project tool window, locate the app -> java -> com.ebookfrenzy.fragmentexample entry and right click on it. From the resulting menu, select the New -> Fragment -> Gallery... option to display the dialog shown in Figure 38-1 below:

Figure 38-1

Select the Fragment (Blank) template before clicking the Next button. On the subsequent screen, name the fragment ToolbarFragment with a layout file named fragment_toolbar:

Figure 38-2

Load the fragment_toolbar.xml file into the layout editor using Design mode, right-click on the FrameLayout entry in the Component Tree panel and select the Convert FrameLayout to ConstraintLayout menu...

38.4 Migrating a Fragment to View Binding

As with the Empty Activity template, Android Studio 4.2 does not enable view binding support when new fragments are added to a project. Before moving to the next step of this tutorial, therefore, we will need to perform this migration. Begin by editing the ToolbarFragment.kt file and importing the binding for the fragment as follows:

import com.ebookfrenzy.fragmentexample.databinding.FragmentToolbarBinding

Next, locate the onCreateView() method and make the following declarations and changes (which also include adding the onDestroyView() method to ensure that the binding reference is removed when the fragment is destroyed):

.

.

private var _binding: FragmentToolbarBinding? = null

private val binding get() = _binding!!

 

override fun onCreateView(

    inflater: LayoutInflater, container: ViewGroup?,

    savedInstanceState: Bundle?

): View? {

   ...

38.5 Adding the Second Fragment

Repeating the steps used to create the toolbar fragment, add another empty fragment named TextFragment with a layout file named fragment_text. Once again, convert the FrameLayout container to a ConstraintLayout (changing the id to constraintLayout2) and remove the default TextView.

Drag a drop a TextView widget from the palette and position it in the center of the layout, using the Infer constraints button to add any missing constraints. Change the id of the TextView to textView2, the text to read “Fragment Two” and modify the textAppearance attribute to Large.

On completion, the layout should match that shown in Figure 38-4:

Figure 38-4

Repeat the steps performed in the previous section to migrate the TextFragment class to use view binding as follows:

.

.

import com.ebookfrenzy.fragmentexample.databinding.FragmentTextBinding

.

.

private var _binding: FragmentTextBinding? = null

private val binding get...

38.6 Adding the Fragments to the Activity

The main activity for the application has associated with it an XML layout file named activity_main.xml. For the purposes of this example, the fragments will be added to the activity using the <fragment> element within this file. Using the Project tool window, navigate to the app -> res -> layout section of the FragmentExample project and double-click on the activity_main.xml file to load it into the Android Studio Layout Editor tool.

With the Layout Editor tool in Design mode, select and delete the default TextView object from the layout and select the Common category in the palette. Drag the FragmentContainerView component from the list of views and drop it onto the layout so that it is centered horizontally and positioned such that the dashed line appears indicating the top layout margin:

Figure 38-5

On dropping the fragment onto the layout, a dialog will appear displaying a list of Fragments available within the...

38.7 Making the Toolbar Fragment Talk to the Activity

When the user touches the button in the toolbar fragment, the fragment class is going to need to get the text from the EditText view and the current value of the SeekBar and send them to the text fragment. As outlined in “An Introduction to Android Fragments”, fragments should not communicate with each other directly, instead using the activity in which they are embedded as an intermediary.

The first step in this process is to make sure that the toolbar fragment responds to the button being clicked. We also need to implement some code to keep track of the value of the SeekBar view. For the purposes of this example, we will implement these listeners within the ToolbarFragment class. Select the ToolbarFragment.kt file and modify it so that it reads as shown in the following listing:

package com.ebookfrenzy.fragmentexample

 

import android.os.Bundle

import androidx.fragment.app.Fragment

import...

38.8 Making the Activity Talk to the Text Fragment

As outlined in “An Introduction to Android Fragments”, an activity can communicate with a fragment by obtaining a reference to the fragment class instance and then calling public methods on the object. As such, within the TextFragment class we will now implement a public method named changeTextProperties() which takes as arguments an integer for the font size and a string for the new text to be displayed. The method will then use these values to modify the TextView object. Within the Android Studio editing panel, locate and modify the TextFragment.kt file to add this new method:

package com.ebookfrenzy.fragmentexample

.

.

class TextFragment : Fragment() {

.

.

    fun changeTextProperties(fontsize: Int, text: String)

    {

        binding.textView2.textSize = fontsize.toFloat()

     &...

38.9 Testing the Application

With the coding for this project now complete, the last remaining task is to run the application. When the application is launched, the main activity will start and will, in turn, create and display the two fragments. When the user touches the button in the toolbar fragment, the onButtonClick() method of the activity will be called by the toolbar fragment and passed the text from the EditText view and the current value of the SeekBar. The activity will then call the changeTextProperties() method of the second fragment, which will modify the TextView to reflect the new text and font size:

Figure 38-9

38.10 Summary

The goal of this chapter was to work through the creation of an example project intended specifically to demonstrate the steps involved in using fragments within an Android application. Topics covered included the use of the Android Support Library for compatibility with Android versions predating the introduction of fragments, the inclusion of fragments within an activity layout and the implementation of inter-fragment communication.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.2 Development Essentials - Kotlin Edition
Published in: Aug 2021 Publisher: Packt ISBN-13: 9781803231549
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}