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

84. An Android HTML and Web Content Printing Example

As outlined in the previous chapter, entitled “Printing with the Android Printing Framework”, the Android Printing framework can be used to print both web pages and dynamically created HTML content. While there is much similarity in these two approaches to printing, there are also some subtle differences that need to be taken into consideration. This chapter will work through the creation of two example applications in order to bring some clarity to these two printing options.

84.1 Creating the HTML Printing Example Application

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 HTMLPrint into the Name field and specify com.ebookfrenzy.htmlprint 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.

84.2 Printing Dynamic HTML Content

The first stage of this tutorial is to add code to the project to create some HTML content and send it to the Printing framework in the form of a print job.

Begin by locating the MainActivity.kt file (located in the Project tool window under app -> java -> com.ebookfrenzy.htmlprint) and loading it into the editing panel. Once loaded, modify the code so that it reads as outlined in the following listing:

package com.ebookfrenzy.htmlprint

 

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.print.PrintAttributes

import android.print.PrintManager

import android.webkit.WebResourceRequest

import android.webkit.WebView

import android.webkit.WebViewClient

import android.content.Context

 

class MainActivity : AppCompatActivity() {

 

    private var myWebView: WebView? = null

 

    override fun onCreate...

84.3 Creating the Web Page Printing Example

The second example application to be created in this chapter will provide the user with an Overflow menu option to print the web page currently displayed within a WebView instance.

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

Enter WebPrint into the Name field and specify com.ebookfrenzy.webprint 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.

84.4 Removing the Floating Action Button

Selecting the Basic Activity template provided a context menu and a floating action button. Since the floating action button is not required by the app it can be removed before proceeding. Load the activity_main.xml layout file into the Layout Editor, select the floating action button and tap the keyboard Delete key to remove the object from the layout. Edit the MainActivity.kt file and remove the floating action button code from the onCreate method as follows:

override fun onCreate(savedInstanceState: Bundle?) {

.

.

   // binding.fab.setOnClickListener { view ->

   // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)

   // .setAction("Action", null).show()

    }

}

84.5 Removing Navigation Features

As outlined in “A Guide to the Android Studio Layout Editor Tool”, the Basic Activity template contains multiple fragments and buttons to navigate from one fragment to the other. For the purposes of this tutorial, these features are unnecessary and will cause problems later if not removed. Before moving ahead with the tutorial, modify the project as follows:

1. Within the Project tool window, navigate to and double-click on the app -> res -> navigation -> nav_graph.xml file to load it into the navigation editor.

2. Within the editor, select the SecondFragment entry in the graph panel and tap the keyboard delete key to remove it from the graph.

3. Locate and delete the SecondFragment.kt (app -> java -> <package name> -> SecondFragment) and fragment_second.xml (app -> res -> layout -> fragment_second.xml) files.

4. Locate the FirstFragment.kt file, double click on it to load it into the editor...

84.6 Designing the User Interface Layout

Load the content_main.xml layout resource file into the Layout Editor tool if it has not already been loaded and, in Design mode, select and delete the nav_host_fragment_content_main object. From the Widgets section of the palette, drag and drop a WebView object onto the center of the device screen layout. Click the Infer constraints toolbar button and, using the Attributes tool window, change the layout_width and layout_height properties of the WebView to match constraint so that it fills the entire layout canvas as outlined in Figure 84-2:

Figure 84-2

Select the newly added WebView instance and change the ID of the view to myWebView.

Before proceeding to the next step of this tutorial, an additional permission needs to be added to the project to enable the WebView object to access the Internet and download a web page for printing. Add this permission by locating the AndroidManifest.xml file in the Project tool window and double...

84.7 Accessing the WebView from the Main Activity

As with the project in the chapter entitled “An Android RecyclerView and CardView Tutorial” we need to be able to use view binding to access a component (in this case myWebView) contained in the content_main.xml file from within the MainActivity class. To be able to access views within the content_main.xml file, we once again need to assign it an id at the point that it is included. Edit the activity_main.xml file and modify the include element so that it reads as follows:

.

.

   <include

        android:id="@+id/contentMain"

        layout="@layout/content_main" />

.

.

84.8 Loading the Web Page into the WebView

Before the web page can be printed, it needs to be loaded into the WebView instance. For the purposes of this tutorial, this will be performed by a call to the loadUrl() method of the WebView instance, which will be placed in a method named configureWebView() and called from within the onStart() method of the MainActivity class. Edit the MainActivity.kt file, therefore, and modify it as follows:

package com.ebookfrenzy.webprint

.

.

import android.webkit.WebView

import android.webkit.WebViewClient

import android.webkit.WebResourceRequest

import android.content.Context

 

class MainActivity : AppCompatActivity() {

.

.

   override fun onStart() {

        super.onStart()

        configureWebView()

    }

 

    private fun configureWebView() {

 

...

84.9 Adding the Print Menu Option

The option to print the web page will now be added to the Overflow menu. The first requirement is a string resource with which to label the menu option. Within the Project tool window, locate the app -> res -> values -> strings.xml file, double-click on it to load it into the editor and modify it to add a new string resource:

<resources>

    <string name="app_name">WebPrint</string>

    <string name="action_settings">Settings</string>

    <string name="print_string">Print</string>

.

.

</resources>

Next, load the app -> res -> menu -> menu_main.xml file into the menu editor, switch to Code mode and replace the Settings menu option with the print option:

<menu xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools=...

84.10 Summary

The Android Printing framework includes extensions to the WebView class that make it possible to print HTML based content from within an Android application. This content can be in the form of HTML created dynamically within the application at runtime, or a pre-existing web page loaded into a WebView instance. In the case of dynamically created HTML, it is important to use a WebViewClient instance to ensure that printing does not start until the HTML has been fully loaded into the WebView.

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}