Figure 3.6: Android support library 2 3.3.2 Configuring the Android SDK Manager The Android SDK Manager manages the various versions of the Android SDK currently installed on your computer. When it is launched, you will see a list of items and whether or not they are currently installed on your computer. Check the relevant tools, documentation, and platforms you need for your project. Once you have selected the items you want, click the Install button to download them. Because it takes a while to download from Google’s server, it is a good idea to download only what you need immediately, and download the rest when you have more time. For now, you may want to check the items shown in the figure. 51 CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 3.7: Configuring the android sdk manager Each version of the Android OS is identified by an API level number. For example, Android 2.3.3 is level 10, while Android 3.0 is level 11, and so on. For each level, two platforms are available. For example, level 14 offers the following: SDK Platform Google APIs by Google Inc. The key difference between the two is that the Google APIs platform contains additional APIs Provided by Google, Therefore, if the application you are writing requires Google Maps, you need to create an AVD using the Google APIs. You will be asked to choose the packages to install. Check the Accept All option and click Install. 3.3.3 Android SDK Features The true appeal of Android as a development environment lies in its APIs. As an application-neutral platform, Android gives you the opportunity to create applications that are as much a part of the phone as anything provided out-of-the-box. The following list highlights 52 CU IDOL SELF LEARNING MATERIAL (SLM)
Some of the most noteworthy Android features: GSM, EDGE, 3G, 4G, and LTE networks for telephony or data transfer, enabling you to make or receive calls or SMS messages, or to send and retrieve data across mobile networks Comprehensive APIs for location-based services such as GPS and network-based location Detection Full support for applications that integrate map controls as part of their user interfaces Wi-Fi hardware access and peer-to-peer connections Full multimedia hardware control, including playback and recording with the camera and microphone Media libraries for playing and recording a variety of audio/video or still-image formats APIs for using sensor hardware, including accelerometers, compasses, and barometers Libraries for using Bluetooth and NFC hardware for peer-to-peer data transfer IPC message passing Shared data stores and APIs for contacts, social networking, calendar, and multi- media Background Services, applications, and processes Home-screen Widgets and Live Wallpaper The ability to integrate application search results into the system searches An integrated open-source HTML5 WebKit-based browser Mobile-optimized, hardware-accelerated graphics, including a path-based 2D graphics library and support for 3D graphics using OpenGL ES 2.0 Localization through a dynamic resource framework An application framework that encourages the reuse of application components and the replacement of native applications Offline Mapping SDK Features-EDUREKA SDK helps in dynamically downloading the maps for more than 190 countries in over 60 languages. You can view these offline, also dealing with the map 53 CU IDOL SELF LEARNING MATERIAL (SLM)
styles and the touch gesture. This SDK also can render raster tiles and map objects interleaved within different map layers. Dynamic Markers Dynamic markers Android SDK Tutorial In the previous versions, you could not have moved the position without a fallback or re-adding the icon. But in the latest edition, you can update the position of the icon dynamically. Improvised API compatibility With the latest release, it is much easier to migrate from the Google Maps Android API. This is another added advantage of using Android SDK in your program. Now that you guys have understood the features, let’s move ahead and look at the SDK tools which play a major role in Android Development. 3.4 APK EXTENSION APK stands for Android Package Kit and it's the file format that Android uses for its apps. Here's everything you need to know. If you have an Android device, you might have heard the term APK and wondered what it means. While you can use Android without ever learning the meaning of APK, studying a bit will help you appreciate the platform further. Android Package is the package file format used by the Android operating system for distribution and installation of mobile apps and middleware. APK files are analogous to other software packages such as APPX in Microsoft Windows or Deb packages in DEBIAN based operating systems like UBUNTU. To make an APK file, a program for Android is first compiled, and then all its parts are packaged into one file. An APK file contains all that program's code resources, assets, certificates, and manifest file. As is the case with many file formats, APK files can have any name needed, provided that the file name ends in \".APK\". APK files are a type of archive file, specifically in zip format packages based on the JAR file format, with .APK as the filename extension. The MIME type associated with APK files is application/VND.ANDROID.PACKAGE-archive. APK files can be installed on Android powered devices just like installing software on PC. When a user downloads and installs an Android application from either an official source or from some other site, they are installing an APK file on their device. A user or developer can also install an APK file directly to a device from a desktop computer, using a communication program such as ADB, or from within a file manager app in a process known as sideloading. By default, the ability to install from unofficial sites or directly from a desktop or file 54 CU IDOL SELF LEARNING MATERIAL (SLM)
manager is disabled for security reasons on most Android devices. Users can enable it by changing the setting \"Unknown sources\" in the Settings menu. 3.4.1 What Is an APK File? APK stands for Android Package. It's the file format that Android uses to distribute and install apps. As a result, APKs contain all the elements that an app needs to install correctly on your device. An APK is an archive file, meaning that it contains multiple files, plus some metadata about them. You're probably familiar with other types of archive files, like ZIP and RAR. Generally, archive files are used to combine multiple files into one, to make them more portable or compress them to save space. When an archive is used to distribute software, it's then called a software package. An APK file is an app created for Android, Google's mobile operating system. Some apps come pre-installed on Android devices, while other apps can be downloaded from Google Play. Apps downloaded from Google Play are automatically installed on your device, while those downloaded from other sources must be installed manually. Typically, users never see APK files because Android handles app installation in the background via Google Play or another app distribution platform. However, there are many websites that offer direct APK file downloads for Android users who want to install apps manually themselves. In this case, you should be careful that you trust the source of the APK file, because malware can be distributed in APK files, just as it can in the case of Windows and EXE files. APK or Android Package Kit is an extension for the Android Package files that are used for distributing applications on Android OS from Google. It is like the .exe files in Windows OS that are used for installing software. The APK files contain all the data of an application ranging from its resources and manifest to the app’s compiled application code. From Play Store, we usually download the apps without ever noticing the word APK. It is because Android takes care of the process of app installation in the background. If you know how to install the apps manually, there are a lot of websites that offer APK files for download. However, you must always be careful about downloading these files because just like .exe files, malware can easily be distributed in APK files as well. How do I install an APK file on my Android device? You can install APK files manually by following these instructions. Make sure that you trust the source of the APK file. 55 CU IDOL SELF LEARNING MATERIAL (SLM)
What does an APK file contain? Android packages contain all the necessary files for a single Android program. Below is a list of the most prominent files and folders: META-INF/: Contains the manifest file, signature, and a list of resources in the archive LIB/: Native libraries that run on specific device architectures res/: Resources, such as images, that were not compiled into resources ARSC assets/: Raw resource files that developers bundle with the app AndroidManifest.xml: Describes the name, version, and contents of the APK file classes.dex: The compiled Java classes to be run on the device Resources ARSC: The compiled resources, such as strings, used by the app How do I view the contents of an APK file? APK files are saved in a compressed .ZIP format and can be opened by any Zip decompression tool. Therefore, if you would like to explore the contents of an APK file, you can rename the file extension to \".zip\" and open the file, or you can open the file directly through a Zip application's open dialog box. 3.4.2 What are APK Files Used for? APK files allow you to install apps on your Android phone. They're similar to the APPX files used to install Store apps on Windows 10, as well as corresponding package files on other platforms. When you open an APK on your device, it contains the instructions to install on your phone, plus provides information about itself to your device. Normally, when you visit Google Play and download an app, the store automatically installs the APK for you. In this way, the Play Store also acts as a package manager a tool for easily installing, updating, and removing software on a device. However, due to Android's open nature, Google Play is not the only way to find and install APKs. It's easy to obtain an APK file from elsewhere, move it to your device, and then install it manually. 3.4.3 How Are APK Files Created? Android apps are developed using Android Studio, the official IDE for Android software developers. It is available for Windows, Mac, and Linux, and it allows users to develop apps and prepare them for upload to a distribution service, such as Google Play. When apps are ready, developers can build them into APK files and sign them for release. 56 CU IDOL SELF LEARNING MATERIAL (SLM)
When a developer creates an Android app, they likely use Android Studio, the official development tool for Android. Once the app is ready to ship, Android Studio compiles the app, and then puts it all into one container an APK. APKs can have any name, but typically need to keep the file extension .APK so OSES know how to interpret them. When you download an APK, you'll usually find they have filenames like the following: com.google.android.dialer_66.0.374464860.apk This is a version of the APK name for Google's Phone app. You can see that the full app name matches up with the app's filename in the URL of its Google Play page: https://play.google.com/store/apps/details?id=com.google.android.dialer The numbers at the end represent the current version, which can be quite granular since major apps like this get updated all the time. 3.4.4 Why Would I Install APK Files Manually? Google Play is fine for most people's Android installation needs. But there are several benefits to installing APKs manually. One of the biggest is getting access to the latest version of apps ahead of time. When a major Google app releases a major update, it can take a week or more for your device to get it from Google Play. Installing the APK on your own lets you skip the wait and update as soon as you want. Sideloading APKs also lets you install apps on your device that aren't available on Google Play. You might find an app that isn't allowed on Google Play because it violates a policy, or maybe you want to test your friend's app that's currently in development. Just like desktop software, though, downloading APK files from random websites can be dangerous. While Google Play has filters in place to catch most dangerous apps, there's not as much protection when you're installing APKs on your own. Only download APKs from trusted sites. Be wary of any page that promises you a paid app for free that's a common tactic to install malware on your device. Risks and Benefits of Installing APK Files in your Android phone If you are an Android user than most likely you have heard about APK files and wondered what it stands for. Understanding this is essential if you want to download apps and customize your device further than it’s possible to do using only Play Store. You will be surprised how many apps and other cool stuff is available for Android but not on Play Store. APK or Android application package is the package file format used by Android operating system for distribution and installation of applications. APK files are analogous to .exe files 57 CU IDOL SELF LEARNING MATERIAL (SLM)
used in Windows to install a software. The APK is the file format used to install software on Android powered devices. Here’s how an APK file is made. First it is compiled and then all the parts are packaged together is a single file. The APK file contains all the necessary files for the software to be installed and work properly. It contains the program’s code, such .DEX files, assets, resources, certificates, and manifest file. An APK file is a kind of an archive file, such as zip format packages based on the JAR file format. But they come with an .APK extension. You can easily change the name of an APK file if it has the .APK extension in the end. By default, the ability to install an APK file from unofficial sites is disabled for security features. But you can enable it easily. Go to Settings > Security > Unknown Sources and tick the box next to it. You better know the benefits and risks of installing an APK file before doing so. Below you will find why sometimes it’s good to download an APK file and why we should be careful when we do it. Pros of Installing an APK File There are several reasons why we go for an APK files. Sometimes new apps are leaked ahead of time. This means you can get the new apps even before they are available on Play Store. You will get early access to all the exciting new features. Have you ever wanted to download an app from Play Story, and it was not available on your country? I guess it has happened, at least one time. Plethora of cool apps is restricted to regions and maybe your country can be one of them. So, the only way to get the app is to download and install the APK file. APK files allow you to get the latest Google update by bypassing carriers. It might be frustrating to wait for the update and it might take a long time to arrive as an OTA (over the air) update. While installing the APK file you will enjoy the latest goodies without worrying whenever your carrier will release an update or not. Cons of Installing APK Files Even though it’s easy to install an APK file it might not be always useful and trusted. Be careful when downloading an APK files. It might be a stolen app and you don’t want to put yourself into troubles. Some APK services allow you to download pirated apps. This is something illegal and you should avoid. Always do some research before downloading an APK file. You don’t want to do something against the law and run yourself into troubles. There are several sources on the internet where you can download APK files. However not all of these are trusted so you must choose carefully. Some APK files may contain malicious 58 CU IDOL SELF LEARNING MATERIAL (SLM)
software that can harm your device. They can compromise your phone security easily and steal your personal information. Hackers can get the APK files, modify it and by just by adding extra app permission they can easily steal information from your device. So, take care, always check app permissions when install and APK file. If it seems suspicious better not install it at all. Also, if you want you can change app permissions on Android without root. Some versions of Android have built-in features but some others not, so you must use third-party apps. Some sites, despite looking trustful they might contain malicious apk files. Always read some user comments and reviews before downloading the APK file. APK mirror is considered as a trusty site but be careful just in case. You know: Better safe than sorry. 3.5 SUMMARY Android sits alongside a new wave of modern mobile operating systems designed to support application development on increasingly powerful mobile hardware. Platforms like Microsoft’s Windows Phone and the Apple IPHONE also provide a richer, simplified development environment for mobile applications; however, unlike Android, they’re built on proprietary operating systems. Android sits alongside a new wave of modern mobile operating systems designed to support application development on increasingly powerful mobile hardware. Platforms like Microsoft’s Windows Phone and the Apple IPHONE also provide a richer, simplified development environment for mobile applications; however, unlike Android, they’re built on proprietary operating systems. Android SDK is a software development kit developed by Google for the Android platform. The Android SDK allows you to create Android apps, and you don't need to be an expert to use it. In this tutorial, I'll explain what the Android SDK is and how to get started with it. APK files are analogous to other software packages such as APPX in Microsoft Windows or Deb packages in DEBIAN based operating systems like UBUNTU. To make an APK file, a program for Android is first compiled, and then all its parts are packaged into one file. An APK file contains all that programs, resources, assets, certificates, and manifest file. As is the case with many file formats, APK files can have any name needed, provided that the file name ends in \"APK\". APK stands for Android Package (sometimes Android Package Kit or Android Application Package). It's the file format that Android uses to distribute and install apps. As a result, APKs contain all the elements that an app needs to install correctly on your device. 59 CU IDOL SELF LEARNING MATERIAL (SLM)
APK or Android application package is the package file format used by Android operating system for distribution and installation of applications. APK files are analogous to .exe files used in Windows to install software. The APK is the file format used to install software on Android powered devices. Here’s how an APK file is made. One of the biggest is getting access to the latest version of apps ahead of time. When a major Google app releases a major update, it can take a week or more for your device to get it from Google Play. Installing the APK on your own lets you skip the wait and update as soon as you want. 3.6 KEYWORDS Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the virtual machine for memory, battery life and performance. Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein. The DEX compiler converts the class files into the .DEX file that run on the Dalvik VM. Multiple class files are converted into one DEX file. Android SDK is a collection of libraries and Software Development tools that are essential for Developing Android Applications. Whenever Google releases a new version or update of Android Software, a corresponding SDK also releases with it. Android Support Library package is a set of code libraries that provide backward- compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to a specific Android API level. Dynamic marks indicate how loud or soft the music should be played. For instrumental parts, dynamic marks are placed under a note beneath the musical staff. For a vocal part, the dynamic mark is placed above a note on top of the musical staff. APK stands for Android Package Kit and it's the file format that Android uses for its apps. Here's everything you need to know. 3.7 LEARNING ACTIVITY 1. Install a New app in your device which you are using for the first time & rate the app with suggestions. ___________________________________________________________________________ __________________________________________________________________________ 60 CU IDOL SELF LEARNING MATERIAL (SLM)
2. Find the Difference between I phone apps & android apps? ___________________________________________________________________________ __________________________________________________________________________ 3.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Describe Installing the Android SDK Tools. 2. State the Android SDK Features. 3. Explain APK File. 4. How Are APK Files Created? 5. Define Dalvik Virtual Machine. Long Questions 1. Why Would I Install APK Files Manually? 2. Explain the Android SDK Features. 3. Describe the Dalvik Virtual Machine. 4. What Are APK Files Used For? Explain Configuring the Android SDK Manager. 5. Briefly explain the Android SDK Tools. B. Multiple Choice Questions 1. Which section provides a key component called Dalvik Virtual Machine? a. Libraries b. Android Runtime c. Application Framework d. Applications 2. Which of the following virtual machine is used by the Android operating system? a. JVM b. Dalvik virtual machine c. Simple virtual machine d. None of these 61 CU IDOL SELF LEARNING MATERIAL (SLM)
3. What does APK stands for? a. Android Phone Kit b. Android Page Kit c. Android Package Kit d. None of these 4. Which of these is not one of the three main components of the APK? a. Dalvik Executable b. Resources c. Native Libraries d. Webkit 5. Where can one while developing Android applications, developers can test their apps on ? a. Emulator included in Android SDK b. Physical Android phone c. Third-party Emulators d. All the these Answer 1-b, 2- b, 3-c, 4- d, 5- d 3.9 REFERENCES Reference Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011 “Programming Android”, O’Reilly books. Erik Hellman, 2013, Android Programming: Pushing the Limits. Neil Smith, 2014, Android Studio Development Essentials. Textbooks Rick Boyer, 2018, Android 9 Development Cookbook: Over 100 Recipes and Solutions to Solve the Most Common Problems Faced by Android Developers, 3rd EditionBook 62 CU IDOL SELF LEARNING MATERIAL (SLM)
Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc, Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc. Websites https://en.wikipedia.org/ https://www.javatpoint.com/ 63 CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT 4: ANDROID PROJECT STRUCTURE STRUCTURE 4.0 Learning Objectives 4.1 Introduction 4.2 Android Project Structure 4.3 Activity and its Life Cycle 4.3.1 Understanding Activities 4.3.2 Understanding the Life Cycle of an Activity 4.4 Summary 4.5 Keywords 4.6 Learning Activity 4.7 Unit End Questions 4.8 References 4.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Explain the Android Project Structure. Explain Activity and its Life Cycle. Realize the Life Cycle of an Activity. 4.1 INTRODUCTION Android application development has never been easy due to its raw nature and rapid growth and changes to the platform. If we cast our memories back a few years, Eclipse was the only IDE used for Android development. Eclipse is developed and maintained by open-source alliance. Due to its open source and free nature, it always failed to match its all-time competitor platform IDE like XCode. But now Android development looks very promising with the introduction of Android Studio IDE. Android Studio is an IDE based on Interlay IDEA that is used for android application development. The initial developer preview was released on 15th May 2013. This tool has more options that will enable developers to speed up application development. In the later section of this tutorial, we will understand the Android Studio project structure in the context of traditional eclipse-based project structure. 64 CU IDOL SELF LEARNING MATERIAL (SLM)
Creating an Android project in Android Studio is as simple as clicking a few buttons. Along the way you will be asked to choose the minimum Android SDK that will be supported by your application. Of course, you are still able to change this while developing your application. Once created, the project files contain various folders and files about project settings as well as your Android Application module. An application can have zero or more activities. Typically, applications have one or more activities; and the main purpose of an activity is to interact with the user. From the moment an activity appears on the screen to the moment it is hidden, it goes through several stages, known as an activity’s life cycle. Understanding the life cycle of an activity is vital to ensuring that your application works correctly. In addition to activities, Android 4.0 also supports a feature that was introduced in Android 3.0 (for tablets): fragments. Think of fragments as “miniature” activities that can be grouped to form an activity. In this chapter, you will learn about how activities and fragments work together. Apart from activities, another unique concept in Android is that of intent. Intent is basically the “glue” that enables different activities from different applications to work together seamlessly, ensuring that tasks can be performed as though they all belong to one single application. Later in this chapter, you will learn more about this very important concept and how you can use it to call built-in applications such as the Browser, Phone, Maps, and more. As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle, The Activity class provides several call backs that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides. Within the lifecycle call-back methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot. In other words, each call-back allows you to perform specific work that's appropriate to a given change of state. Doing the right work at the right time and handling transitions properly make your app more robust and perform ant. 4.2 ANDROID PROJECT STRUCTURE Creating an Android project in Android Studio is as simple as clicking a few buttons. Along the way you will be asked to choose the minimum Android SDK that will be supported by your application. Of course, you are still able to change this while developing your application. 65 CU IDOL SELF LEARNING MATERIAL (SLM)
Once created, the project files contain various folders and files about project settings as well as your Android Application module. Figure 4.1: ANDROID PROJECT STRUCTURE 1. Main Project This would be the entire project context. Whatever you do in Interlay IDEA, you do that in the context of a project. A project is an organizational unit that represents a complete software solution. A project in Android Studio is like a workspace in Eclipse. In Android Studio a project can contain multiple modules. A module in Android Studio is like a project in Eclipse. In the above screenshot, “Login Authenticator” is the name of my project this means that, in theory, it is possible to build multiple apps within the same project. From my personal experience, creating multiple apps within the same project doesn’t work well. So, I recommend not making your hands dirty trying the same thing. Instead, it is a better idea to create a single app per single project. 2. IDEA Eclipse uses project. Properties file for project-specific metadata. Here in the Android studio, this idea does the same thing. This means the project-specific metadata is stored by Android Studio. 3. Project Module This is the actual project folder where your application code resides. The application folder has following sub directories BUILD:This has all the complete output of the make process i.e., classes.dex, compiled classes and resources, etc. 66 CU IDOL SELF LEARNING MATERIAL (SLM)
In the Android Studio GUI, only a few folders are shown. The important part is that your R.java is found here under build/source/r/<build variant>/<package>/R.java LIBS: This is a commonly seen folder in eclipse land too, which optionally can hold the libraries or .jar files. SRC: The SRC folder can have both application code and android unit test script. You will find two folders named “androidTest” and “main” correspond to the “SRC” folder. The main folder contains two subfolders java and res. The java folder contains all the java codes and re contains layouts. 4. GRADLE This is where the GRADLE build system’s jar wrapper i.e., this jar is how AS communicates with GRADLE installed in Windows. 5. External Libraries This is not actually a folder but a place where Referenced Libraries and information on targeted platform SDK is shown. Basic Android Project Structure After you have installed all the plug-ins necessary for the development of an Android file, you can now begin to develop an Android application. From the top menu, choose File -> Project, and from the \"New Project window\", choose \"Android Project\". Follow the project setup wizard and after finishing the wizard, you will have a basic Android application. Every Android project contains several folders: SRC: This folder contains the Java source files. GEN: Generated Java library, this library is for Android internal use only. RES: Here we can store resource files such as pictures, XML files for defining layouts, and so forth. Within this folder there are additional folders such as Draw able, Layout, and Values. DRAWABLE: Here we store the various graphic files. We can see three types of draw able folders. This is because there are many Android devices with different screen resolutions. By default, there are several versions of this folder such as: DRAWABLE-MDPI, DRAWABLE-HDPI, and so forth. This is required to adapt to different screen resolutions. Layout: This is the place for XML layout files. Layout files are XML files which define how various Android objects (such as textboxes, buttons, etc.) are organized on the screen. Values: XML files which store various string values (titles, labels, etc.). 67 CU IDOL SELF LEARNING MATERIAL (SLM)
Major Files in the Android Project: AndroidManifest.xml: This is the Android definition file. It contains information about the Android application such as minimum Android version, permission to access Android device capabilities such as internet access permission, ability to use phone permission, etc. MainLayout.xml: This file describes the layout of the page. This means the placement of every component (such as textboxes, labels, radio buttons, user defined components, etc.) on the app screen. Activity class: Every application that occupies the entire device screen needs at least one class which inherits from the Activity class. One major method is called OnCreate. This method initiates the app and loads the layout page. The Android Manifest File A typical ANDROID.MANIFEST file looks like this: XML Copy Code <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.firstproject\" android:versionCode=\"1\" android:versionName=\"1.0\" > <uses-sdk android:minSdkVersion=\"7\" /> <application android:icon=\"@drawable/ic_launcher\" android:label=\"@string/app_name\" > <activity android:name=\".MynewprojectActivity\" android:label=\"@string/app_name\" > <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> 68 CU IDOL SELF LEARNING MATERIAL (SLM)
</activity> </application> </manifest> Some Important Definitions in this File: Android:versionCode: This is a numerical value. This is an important attribute because that is how the Android device knows when to alert the user to upgrade the application to a newer version. Android: SDK Min Version: Defines what is the earliest version of the Android operating system available to this application? Activity element: Defines what the activities available in this application are and which activity must be loaded at startup Layout File A typical layout file looks like this: XML Copy Code <? xml version=\"1.0\" encoding=\"utf-8\"?> <Linear Layout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill parent\" android:layout_height=\"fill parent\" android: orientation=\"vertical\" > <Text View android:layout_width=\"fill parent\" android:layout_height=\"wrap content\" android: text=\"@string/hello\"/> </Linear Layout> This layout defines one object, a TextView. This is a text label, and it is used when a programmer wants to place a text title in your application. Activity Class One major class is the Activity class. We already defined this class in the android. Manifest file as the main activity class. Which is the first class to be loaded and executed right after the Android application will be launched: 69 CU IDOL SELF LEARNING MATERIAL (SLM)
Java Copy Code package com.firstproject; import android.ap.Activity; import android OS Bundle; public class Mynewproject Activity extends Activity Called when the activity is first created. Override public void on Create super on Create setContent View; We can see here one major method called \"onCreate\" which is called when the Activity class is activated. In our specific example, we define a layout file by the line set Content View. Let's have some code We want to change the text in the label from \"Hello World\" to Hello \"New Application\". First, we must link the label in the layout to a Java object. Before that we must give an ID to our label object. This is done by opening our layout file, which is called in our specific project \"main.xml\" and is in the \"res/layout\" folder. In the \"TextView\" element, we must add the following attribute: Copy Code android:id=\"@+id/myLabel\" After that, let's open out main activity class, which in our case is called \"MyfirstandroidprojectActivity.java\" and add the following line in the \"OnCreate\" method: Java Copy Code TextView mTextView =this. find ViewBy Id M Text View setText(\"Hello my New Project\"); The first line defines the linkage between the \"TextView\" object on the screen and the Java TextView object, and the second line defines the text string in the \"TextView\" object. 70 CU IDOL SELF LEARNING MATERIAL (SLM)
4.3 ACTIVITY AND ITS LIFE CYCLE A Closer Look at Android Activities Each Activity represents a screen that an application can present to its users. The more complicated your application, the more screens you are likely to need. Typically, this includes at least a primary interface screen that handles the main UI functionality of your application. This primary interface generally consists of several Fragments that make up your UI and is generally supported by a set of secondary Activities. To move between screens, you start a new Activity. Most Activities are designed to occupy the entire display, but you can also create semi-transparent or floating Activities. 4.3.1 Understanding Activities This chapter begins by looking at how to create an activity. To create an activity, you create a Java class that extends the Activity base class: package net.learn2develop.Activity101; import android.app.Activity; import android.os.Bundle; public class Activity101Activity extends Activity { Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Your activity class loads its UI component using the XML fi le defi ned in your res/layout folder. In this example, you would load the UI from the main.xml fi le: setContentView(R.layout.main); Every activity you have in your application must be declared in your AndroidManifest.xml fi le, like this: <? Xmlversion=“1.0“ encoding=“utf-8“? <manifest xmlns:android=“http://schemas.android.com/apk/res/android“ package=”net.learn2develop.Activity101” 71 CU IDOL SELF LEARNING MATERIAL (SLM)
android:versionCode=”1” android:versionName=”1.0” <uses-sdk android:minSdkVersion=”14” <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” <activity android:label=”@string/app_name” android:name=”.Activity101Activity” <intent-filter > <action android:name=”android.intent.action.MAIN” <category android:name=”android.intent.category.LAUNCHER” </intent-filter> </activity> </application> </manifest> The Activity base class defines a series of events that govern the life cycle of an activity,theActivity class defines the following events: OnCreate- Called when the activity is fi rst created OnStart- Called when the activity becomes visible to the user OnResume- Called when the activity starts interacting with the user OnPause- Called when the current activity is being paused and the previous activity is being resumed OnStop - Called when the activity is no longer visible to the user OnDestroy- Called before the activity is destroyed by the On Restart - Called when the activity has been stopped and is restarting again. By default, the activity created for you contains the on Create event. Within this event handler is the code that helps to display the UI elements of your screen. 72 CU IDOL SELF LEARNING MATERIAL (SLM)
The Activity class defines the following call backs i.e., events. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Sr.No Callback & Description On Create 1 This is the first callback and called when the activity is first created. On Start 2 This callback is called when the activity becomes visible to the user. On Resume 3 This is called when the user starts interacting with the application. On Pause 4 The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. On Stop 5 This callback is called when the activity is no longer visible. On Destroy 6 This callback is called before the activity is destroyed by the system. On Restart 73 7 This callback is called when the activity restarts after stopping it. Table- 4.1 Understanding activities CU IDOL SELF LEARNING MATERIAL (SLM)
4.3.2 Understanding the Life Cycle of an Activity A good understanding of the Activity lifecycle is vital to ensure that your application provides a seamless user experience and properly manages its resources. As explained earlier, Android applications do not control their own process lifetimes; the Android run time manages the process of each application, and by extension that of each Activity within it. Although the run time handles the termination and management of an Activity’s process, the Activity’s state helps determine the priority of its parent application. The application priority, in turn, influences the likelihood that the run time will terminate it and the Activities running within it. As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle, The Activity class provides several callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides. Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot. In other words, each callback allows you to perform specific work that's appropriate to a given change of state. Doing the right work at the right time and handling transitions properly make your app more robust and perform ant. For example, good implementation of the lifecycle callbacks can help ensure that your app avoids: Crashing if the user receives a phone call or switches to another app while using your app. Consuming valuable system resources when the user is not actively using it. Losing the user's progress if they leave your app and return to it later. Crashing or losing the user's progress when the screen rotates between landscape and portrait orientation. This document explains the activity lifecycle in detail. The document begins by describing the lifecycle paradigm. Next, it explains each of the call backs what happens internally while they execute, and what you should implement during them. It then briefly introduces the relationship between activity state and a process’s vulnerability to being killed by the system. Last, it discusses several topics related to transitions between activity states. For information about handling lifecycles, including guidance about best practices, seeHandling Lifecycles with Lifecycle-Aware Components and Saving UI States. To learn 74 CU IDOL SELF LEARNING MATERIAL (SLM)
how to architect a robust, production-quality app using activities in combination with architecture components, see Guide to App Architecture. Figure 4.2: A simplified illustration of the activity lifecycle As the user begins to leave the activity, the system calls methods to dismantle the activity. In some cases, this dismantlement is only partial; the activity still resides in memory (such as when the user switches to another app), and can still come back to the foreground. If the user returns to that activity, the activity resumes from where the user left off. With a few exceptions, apps are restricted from starting activities when running in the background. The system’s likelihood of killing a given process along with the activities in it depends on the state of the activity at the time. Activity state and ejection from memory provides more information on the relationship between state and vulnerability to ejection. 75 CU IDOL SELF LEARNING MATERIAL (SLM)
Depending on the complexity of your activity, you probably don't need to implement all the lifecycle methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. The next section of this document provides detail on the callbacks that you use to handle transitions between states. Lifecycle callbacks This section provides conceptual and implementation information about the callback methods used during the activity lifecycle. Some actions, such as calling setContent View, belong in the activity lifecycle methods themselves. However, the code implementing the actions of a dependent component should be placed in the component itself. To achieve this, you must make the dependent component lifecycle aware. See Handling Lifecycles with Lifecycle Aware Components to learn how to make your dependent components lifecycle Aware On Create You must implement this call-back, which fires when the system first creates the activity. On activity creation, the activity enters the Created state. In the on Create method, you perform basic application start-up logic that should happen only once for the entire life of the activity. For example, your implementation of on Create might bind data to lists, associate the activity with a View Model, and instantiate some class- scope variables. This method receives the parameter saved Instance State, which is a Bundle object containing the activity's previously saved state. If the activity has never existed before, the value of the Bundle object is null. If you have a lifecycle-aware component that is hooked up to the lifecycle of your activity it will receive the ON CREATE event. The method annotated with @ONLIFECYCLEEVENT will be called so your lifecycle-aware component can perform any setup code it needs for the created state. As an alternative to defining the XML file and passing it to set Content View, you can create new View objects in your activity code and build a view hierarchy by inserting new Views into a ViewGroup. You then use that layout by passing the root ViewGroup to setContent View. For more information about creating a user interface, see the User Interface documentation. Your activity does not reside in the Created state. After the on Create method finishes execution, the activity enters the Started state, and the system calls the on Start and on Resume methods in quick succession. The next section explains the on Start callback. 76 CU IDOL SELF LEARNING MATERIAL (SLM)
On Start When the activity enters the Started state, the system invokes this callback. The on Start call makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the app initializes the code that maintains the UI. When the activity moves to the started state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON START event. The on Start method completes very quickly and, as with the Created state, the activity does not stay resident in the Started state. Once this callback finishes, the activity enters the Resumed state, and the system invokes the on-Resume method. On Resume When the activity enters the Resumed state, it comes to the foreground, and then the system invokes the on-Resume callback. This is the state in which the app interacts with the user. The app stays in this state until something happens to take focus away from the app. Such an event might be, for instance, receiving a phone call, the user’s navigating to another activity, or the device screen’s turning off. When the activity moves to the resumed state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON RESUME event. This is where the lifecycle components can enable any functionality that needs to run while the component is visible and, in the foreground, such as starting a camera preview. When an interruptive event occurs, the activity enters the Paused state, and the system invokes the on-Pause callback. If the activity returns to the Resumed state from the Paused state, the system once again calls on Resume method. For this reason, you should implement onResumeto initialize components that you release during on Pause and perform any other initializations that must occur each time the activity enters the Resumed state. On Pause The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed); it indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode). Use the on Pause method to pause or adjust operations that should not continue (or should continue in moderation) while the Activity is in the Paused state, and that you expect to resume shortly. There are several reasons why an activity may enter this state. For example: 77 CU IDOL SELF LEARNING MATERIAL (SLM)
Some event interrupts app execution, as described in the on Resume section. This is the most common case. On Stop When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the on Stop callback. This may occur, for example, when a newly launched activity covers the entire screen. The system may also call on Stop when the activity has finished running, and is about to be terminated. When the activity moves to the stopped state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_STOP event. This is where the lifecycle components can stop any functionality that does not need to run while the component is not visible on the screen. ON Destroy On Destroy is called before the activity is destroyed. The system invokes this callback either because: the activity is finishing, or the system is temporarily destroying the activity due to a configuration change When the activity moves to the destroyed state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_DESTROY event. This is where the lifecycle components can clean up anything it needs to before the Activity is destroyed. Activity State and Ejection from Memory The system kills processes when it needs to free up RAM; the likelihood of the system killing a given process depends on the state of the process at the time. Process state, in turn, depends on the state of the activity running in the process. Table 1 shows the correlation among process state, activity state, and likelihood of the system’s killing the process. Relationship Between Process Lifecycle and Activity State The system never kills an activity directly to free up memory. Instead, it kills the process in which the activity runs, destroying not only the activity but everything else running in the process, as well. To learn how to preserve and restore your activity's UI state when system- initiated process death occurs, see saving and restoring activity state. A user can also kill a process by using the Application Manager under Settings to kill the corresponding app. For more information about processes in general, see Processes and Threads. For more information about how the lifecycle of a process is tied to the states of the activities in it, see the Process Lifecycle section of that page. 78 CU IDOL SELF LEARNING MATERIAL (SLM)
Saving and Restoring Transient UI State A user expects an activity’s UI state to remain the same throughout a configuration change, such as rotation or switching into multi-window mode. However, the system destroys the activity by default when such a configuration change occurs, wiping away any UI state stored in the activity instance. Similarly, a user expects UI state to remain the same if they temporarily switch away from your app to a different app and then come back to your app later. However, the system may destroy your application’s process while the user is away, and your activity is stopped. Instance State There are a few scenarios in which your activity is destroyed due to normal app behaviour, such as when the user presses the Back button or your activity signals its own destruction by calling the finish method. When your activity is destroyed because the user presses back or the activity finishes itself, both the systems and the user's concept of that Activity instance is gone forever. In these scenarios, the user's expectation matches the system's behaviour and you do not have any extra work to do. Save Simple, Lightweight UI State Using on SaveInstance State As your activity begins to stop, the system calls the onSaveInstance State method so your activity can save state information to an instance state bundle. The default implementation of this method saves transient information about the state of the activity's view hierarchy, such as the text in an EditText widget or the scroll position of a ListView widget. Restore Activity UI State Using Saved Instance State When your activity is recreated after it was previously destroyed, you can recover your saved instance state from the Bundle that the system passes to your activity. Both the on Create and onRestoreInstance State callback methods receive the same Bundle that contains the instance state information. Navigating Between Activities An app is likely to enter and exit an activity, perhaps many times, during the app’s lifetime. For example, the user may tap the device’s Back button, or the activity may need to launch a different activity. This section covers topics you need to know to implement successful activity transitions. These topics include starting an activity from another activity, saving activity state, and restoring activity state. Starting One Activity From Another An activity often needs to start another activity at some point. This need arises, for instance, when an app needs to move from the current screen to a new one. 79 CU IDOL SELF LEARNING MATERIAL (SLM)
Depending on whether your activity wants a result back from the new activity it’s about to start, you start the new activity using either the start Activity or the startActivity for Result method. In either case, you pass in an Intent object. 4.4 SUMMARY Android application development is never been easy due to its raw nature and rapid growth and changes to the platform. If we cast our memories back a few years, Eclipse was the only IDE used for Android development. Eclipse is developed and maintained by open source alliance. Due to its open source and free nature, it always failed to match its all-time competitor platform IDE like XCode. As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle. The Activity class provides a number of call backs that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides. This would be the entire project context. Whatever you do in Interlay IDEA, you do that in the context of a project. A project is an organizational unit that represents a complete software solution. A project in Android Studio is like a workspace in Eclipse. In Android Studio a project can contain multiple modules. A module in Android Studio is like a project in Eclipse. In the above screenshot, “Login Authenticator” is the name of my project this means that, in theory, it is possible to build multiple apps within the same project. From my personal experience, creating multiple apps within the same project doesn’t work well. So, I recommend not making your hands dirty trying the same thing. Instead, it is a better idea to create a single app per single project. Creating an Android project in Android Studio is as simple as clicking a few buttons. Along the way you will be asked to choose the minimum Android SDK that will be supported by your application. Of course, you are still able to change this in the course of developing your application. Each Activity represents a screen that an application can present to its users. The more complicated your application, the more screens you are likely to need. Typically, this includes at least a primary interface screen that handles the main UI functionality of your application. This primary interface generally consists of a number of Fragments that make up your UI and is generally supported by a set of secondary Activities. 80 CU IDOL SELF LEARNING MATERIAL (SLM)
The best way to understand the various stages of an activity is to create a new project, implement the various events, and then subject the activity to various user interactions. A good understanding of the Activity lifecycle is vital to ensure that your application provides a seamless user experience and properly manages its resources. 4.5 KEYWORDS Module is a collection of source files and builds settings that allow you to divide your project into discrete units of functionality. Your project can have one or many modules and one module may use another module as a dependency. Each module can be independently built, tested, and debugged. Activity represents a single screen with a user interface just like window or frame of Java. Android activity is the subclass of ContextThemeWrapper class. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main function. Activity Lifecycle is controlled by 7 methods of android app Activity class. The android Activity is the subclass of ContextThemeWrapper class. Random-access memory (RAM) is a form of computer memory that can be read and changed in any order, typically used to store working data and machine code. A random-access memory device allows data items to be read or written in almost the same amount of time irrespective of the physical location of data inside the memory, in contrast with other direct-access data storage media (such as hard disks, CD-RWs, DVD-RWs and the older magnetic tapes and drum memory), where the time required to read and write data items varies significantly depending on their physical locations on the recording medium, due to mechanical limitations such as media rotation speeds and arm movement.. SIM stands for subscriber identity module and it's a small plastic card that slots into your phone. 4.6 LEARNING ACTIVITY 1. Conduct anonline survey on Android Phone users. ___________________________________________________________________________ __________________________________________________________________________ 2. What is the costliest raw material in the smartphone? 81 CU IDOL SELF LEARNING MATERIAL (SLM)
___________________________________________________________________________ __________________________________________________________________________ 4.7 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Define Activities. 2. Write a short note on Android Project Structure. 3. Define Life Cycle of an Activity. 4. Explain Basic Android project structure. 5. Give an overview of the Life Cycle of an Activity. Long Questions 1. Describe Activities. 2. Discuss the Android Project Structure. 3. How youUnderstanding the Life Cycle of an Activity? 4. Explain the Activity-lifecycle concepts. 5. Give an overview of Life Cycle of an Activity. B. Multiple Choice Questions 1. Which of the following android component displays the part of an activity on screen? a. View b. Manifest c. Intent d. Fragment. 2. Which of the following is the parent class of Activity? a. context b. object c. contextThemeWrapper d. None of these 3. Which of the following is not an activity lifecycle callback method? 82 a. OnClick method CU IDOL SELF LEARNING MATERIAL (SLM)
b. on Create method c. on Start method d. on Back Pressed method 4. Which of the following is the first callback method that is invoked by the system during an activity life-cycle? a. On Click method b. On Create method c. On Start method d. On Restart method 5. What is an activity in android? a. android class b. android package c. A single screen in an application with supporting java code d. None of the these Answer 1-d, 2- c, 3-d, 4- b, 5- c 4.8 REFERENCES Reference Dave Smith and Geoff Friesen, 2011, Android Recipes: A Problem-Solution Approach. Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011 “Programming Android”, O’Reilly books. Dan Gookin, 2013, Android Tablets for Dummies Book. Textbooks Mike Dunn and Shaun Lewis, 2019, Native Mobile Development: A Cross-Reference for IOS and Android. Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc. 83 CU IDOL SELF LEARNING MATERIAL (SLM)
Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc. Websites https://en.wikipedia.org/ https://developer.android.com/ https://www.geeksforgeeks.org/ https://medium.com/ 84 CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT 5: ANDROID VIEW PART 1 STRUCTURE 5.0 Learning Objectives 5.1 Introduction 5.2 View 5.3 Layouts 5.3.1 Linear 5.3.2 Relative 5.3.3 Constraint 5.4 UI Controls 5.4.1 Text View 5.4.2 Edit Text 5.5 Summary 5.6 Keywords 5.7 Learning Activity 5.8 Unit End Questions 5.9 References 5.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Explain the UI Controls. Understand about Layouts. Explain Text View & Edit Text. Elaborate Linear, Relative, & Constraint. 5.1 INTRODUCTION This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components. The 85 CU IDOL SELF LEARNING MATERIAL (SLM)
ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views and define their layout properties. All the interaction of a user with the Android application is through the user interface (UI), hence it is very important to understand the basics about the User Interface of an android application. We have already learned about the various Views available in Android OS to create various UI components of your Android App. The range of screen sizes and display resolutions your application may be used on has expanded along with the range of Android devices now available to buy. Android 3.0 introduced the Fragment API to provide better support for creating dynamic layouts that can be optimized for tablets as well as a variety of different smartphone displays. You’ll learn how to use Fragments to create layouts that scale and adapt to accommodate a variety of screen sizes and resolutions, as well as the best practices for developing and testing your UIs so that they look great on all screens. After being introduced to some of the visual controls available from the Android SDK, you’ll learn how to extend and customize them. Using View Groups, you’ll combine Views to create atomic, reusable UI elements made up of interacting sub controls. You’ll also create your own Views, to display data and interact with users in creative new ways. Finally, you’ll examine Adapters and learn how to use them to bind your presentation layer to the underlying data sources The basic building block for user interface is a View object which is created from the View class and occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components like buttons, text fields, etc. The ViewGroup is a subclass of View and provides invisible container that hold other Views or other ViewGroups and define their layout properties. At third level we have different layouts which are subclasses of ViewGroup class, and a typical layout defines the visual structure for an Android user interface and can be created either at run time using View/ViewGroup objects or you can declare your layout using simple XML file main_layout.xml which is in the res/layout folder of your project. But how will you arrange all those view components to appear in an ordered manner on the device screen. Android Layouts are used to arrange the views on the device's screen. Input controls are the interactive components in your app's user interface. Android provides a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check box, and zoom buttons, toggle buttons, and many more. A View is an object that draws something on the screen that the user can interact with, and a ViewGroup is an object that holds other View (and ViewGroup) objects to define the layout of the user interface. 86 CU IDOL SELF LEARNING MATERIAL (SLM)
5.2 VIEW Developer Guides For information about using this class to develop your application's user interface, read the User Interface developer guide. Using Views All of the views in a window are arranged in a single tree. You can add views either from code or by specifying a tree of views in one or more XML layout files. There are many specialized subclasses of views that act as controls or can display text, images, or other content. Once you have created a tree of views, there are typically a few types of common operations you may wish to perform: Set properties: for example, setting the text of a TextView. The available properties and the methods that set them will vary among the different subclasses of views. Note that properties that are known at build time can be set in the XML layout files. Set focus: The framework will handle moving focus in response to user input. To force focus to a specific view, call request Focus. Set up listeners: Views allow clients to set listeners that will be notified when something interesting happens to the view. For example, all views will let you set a listener to be notified when the view gains or losses focus. You can register such a listener using setOnFocus Listener. Other view subclasses offer more specialized listeners. For example, a Button exposes a listener to notify clients when the button is clicked. Set visibility: You can hide or show views using set Visibility. Note: The Android framework is responsible for measuring, lying out and drawing views. You should not call methods that perform these actions on views yourself unless you are implementing a ViewGroup. Implementing a Custom View To implement a custom view, you will usually begin by providing overrides for some of the standard methods that the framework calls on all views. You do not need to override all of these methods. In fact, you can start by just overriding on Draw. IDs Views may have an integer id associated with them. These kids are typically assigned in the layout XML files and are used to find specific views within the view tree. A common pattern is to: 87 CU IDOL SELF LEARNING MATERIAL (SLM)
Define a Button in the layout file and assign it a unique ID. <Button android:id=\"@+id/my_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/my_button_text\"/> From then onCreate method of an Activity, find the Button Button myButton = findViewby Id; View IDs need not be unique throughout the tree, but it is good practice to ensure that they are at least unique within the part of the tree you are searching. Position The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel. It is possible to retrieve the location of a view by invoking the methods get Left get Top. The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when get Left returns 20 that means the view is located 20 pixels to the right of the left edge of its direct parent. In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight,and get Bottom. These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling get Right is like the following computation: get Left + get Width see Size for more information about the width. Size, Padding and Margins The size of a view is expressed with a width and a height. A view possesses two pairs of width and height values. The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent. The measured dimensions can be obtained by calling getMeasured Width and getMeasured Height. The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling get Width and get Height 88 CU IDOL SELF LEARNING MATERIAL (SLM)
To measure its dimensions, a view considers its padding. The padding is expressed in pixels for the left, top, right, and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the set Padding or setPaddingRelativemethod and queried by calling get Padding Left, getPadding Top, getPadding Right, getPadding Bottom, getPadding Start, getPadding End. Even though a view can define padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup. Layout Layout is a two-pass process: a measure pass and a layout pass. The measuring pass is implemented in measure and is a top-down traversal of the view tree. Each view pushes dimension specifications down the tree during the recursion. At the end of the measure pass, every view has stored its measurements. The second pass happens in layout and is also top- down. During this pass each parent is responsible for positioning all its children using the sizes computed in the measure pass. When a view's measure method returns, it’s getMeasured Width and getMeasured Height values must be set, along with those for all that view's descendants. A view's measured width and measured height values must respect the constraints imposed by the view's parents. This guarantees that at the end of the measure pass, all parents accept all their children's measurements. A parent view may call measure more than once on its children. For example, the parent may measure each child once with unspecified dimensions to find out how big they want to be, and then call measure on them again with actual numbers if the sum of all the children's unconstrained sizes is too big or too small. The measure pass uses two classes to communicate dimensions. The MeasureSpec class is used by views to tell their parents how they want to be measured and positioned. The base LayoutPrams class just describes how big the view wants to be for both width and height. For each dimension, it can specify one of: An exact number MATCH_PARENT, which means the view wants to be as big as its parent (minus padding) WRAP_CONTENT, which means that the view wants to be just big enough to enclose its content (plus padding). There are subclasses of Layout Prams for different subclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of Layout Prams which adds an X and Y value. MeasureSpecs are used to push requirements down the tree from parent to child. A MeasureSpec can be in one of three modes: 89 CU IDOL SELF LEARNING MATERIAL (SLM)
UNSPECIFIED: This is used by a parent to determine the desired dimension of a child view. For example, a LinearLayout may call measure on its child with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how tall the child view wants to be given a width of 240 pixels. EXACTLY: This is used by the parent to impose an exact size on the child. The child must use this size, and guarantee that all its descendants will fit within this size. AT_MOST: This is used by the parent to impose a maximum size on the child. The child must guarantee that it and all its descendants will fit within this size. To initiate a layout, call request Layout. This method is typically called by a view on itself when it believes that it can no longer fit within its current bounds. Drawing Drawing is handled by walking the tree and recording the drawing commands of any View that needs to update. After this, the drawing commands of the entire tree are issued to screen, clipped to the newly damaged area. The tree is largely recorded and drawn in order, with parents drawn before (i.e., behind) their children, with siblings drawn in the order they appear in the tree. If you set a background draw able for a View, then the View will draw it before calling back to its on Draw method. The child drawing order can be overridden with custom child drawing order in a View Group, and with set on Views. To force a view to draw, call invalidates. Event Handling and Threading The basic cycle of a view is as follows: An event comes in and is dispatched to the appropriate view. The view handles the event and notifies any listeners. If while processing the event, the view's bounds may need to be changed, the view will call request Layout. Similarly, if while processing the event the view's appearance may need to be changed, the view will call invalidate. If either request Layout or invalidate were called, the framework will take care of measuring, lying out, and drawing the tree as appropriate. If you are doing work on other threads and want to update the state of a view from that thread, you should use a Handler. 90 CU IDOL SELF LEARNING MATERIAL (SLM)
Focus Handling The framework will handle routine focus movement in response to user input. This includes changing the focus as views are removed or hidden or as new views become available. Views indicate their willingness to take focus through the Focusable method. To change whether a view can take focus, call setFocusable. When in touch mode views indicate whether they still would like focus via isFocusable in Touch Mode and can change this via setFocusableinTouchMode. Focus movement is based on an algorithm which finds the nearest neighbourin each direction. In rare cases, the default algorithm may not match the intended behaviour of the developer. In these situations, you can provide explicit overrides by using these XML attributes in the layout file. Touch Mode When a user is navigating a user interface via directional keys such as a D-pad, it is necessary to give focus to actionable items such as buttons so the user can see what will take input. If the device has touch capabilities, however, and the user begins interacting with the interface by touching it, it is no longer necessary to always highlight, or give focus to, a particular view. This motivates a mode for interaction named 'touch mode'. For a touch capable device, once the user touches the screen, the device will enter touch mode. From this point onward, only views for which isFocusableInTouch Mode is true will be focusable, such as text editing widgets. Other views that are touchable, like buttons, will not take focus when touched; they will only fire the one click listeners. Any time a user hits a directional key, such as a D-pad direction, the view device will exit touch mode, and find a view to take focus, so that the user may resume interacting with the user interface without touching the screen again. The touch mode state is maintained across Activities. Call isInTouch Mode to see whether the device is currently in touch mode. Scrolling The framework provides basic support for views that wish to internally scroll their content. This includes keeping track of the X and Y scroll offset as well as mechanisms for drawing scrollbars. See scroll By, scroll To, and awakenScroll Bars for more details. Tags Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure. 91 CU IDOL SELF LEARNING MATERIAL (SLM)
Themes By default, Views are created using the theme of the Context object supplied to their constructor; however, a different theme may be specified by using the android theme attribute in layout XML or by passing a ContextThemeWrapper to the constructor from code. When the android theme attribute is used in XML, the specified theme is applied on top of the inflation context's theme and used for the view itself as well as any child elements. Properties The View class exposes an ALPHA property, as well as several transform-related properties, such as TRANSLATION_X and TRANSLATION_Y. These properties are available both in the Property form as well as in similarly-named setter/getter methods. These properties can be used to set persistent state associated with these rendering-related properties on the view. The properties and methods can also be used in conjunction with Animator-based animations, described more in the Animation section. Animation Starting with Android 3.0, the preferred way of animating views is to use the android animation package APIs. These Animator-based classes change actual properties of the View object, such as alpha and translationX. This behaviour is contrasted to that of the pre-3.0 Animation-based classes, which instead animate only how the view is drawn on the display. In particular, the ViewPropertyAnimator class makes animating these View properties particularly easy and efficient. Start Animation. The animation can alter the scale, rotation, translation, and alpha of a view over time. If the animation is attached to a view that has children, the animation will affect the entire subtree rooted by that node. When an animation is started, the framework will take care of redrawing the appropriate views until the animation completes. Security Sometimes it is essential that an application be able to verify that an action is being performed with the full knowledge and consent of the user, such as granting a permission request, making a purchase, or clicking on an advertisement. Unfortunately, a malicious application could try to spoof the user into performing these actions, unaware, by concealing the intended purpose of the view. As a remedy, the framework offers a touch filtering mechanism that can be used to improve the security of views that provide access to sensitive functionality. To enable touch filtering, call setFilterTouchesWhenObscured (Boolean) or set the android filterTouchesWhenObscured layout attribute to true. When enabled, the framework will discard touches that are received whenever the view's window is obscured by another visible 92 CU IDOL SELF LEARNING MATERIAL (SLM)
window. As a result, the view will not receive touches whenever a toast, dialog or other window appears above the view's window. For more fine grained control over security, consider overriding the onFilter TouchEvent for Security method to implement your own security policy. 5.3 LAYOUTS Layout Managers are extensions of the View Group class and are used to position child Views within your UI. Layouts can be nested, letting you create arbitrarily complex UIs using a combination of layouts. The Android SDK includes several layout classes. You can use these, modify them, or create your own to construct the UI for your Views, Fragments, and Activities. It’s up to you to select and use the right combination of layouts to make your UI aesthetically pleasing, easy to use, and efficient to display. Example: Layout can be defined as follows:- <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout android:id=\"@+id/layout2\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:background=\"#8ED3EB\" android:gravity=\"center\" android:orientation=\"vertical\" > <TextView android:id=\"@+id/textView4\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"-40dp\" android:fontFamily=\"@font/almendra_bold\" android:text=\"This is a TextView\" /> </LinearLayout> 93 CU IDOL SELF LEARNING MATERIAL (SLM)
The following list includes some of the most used layout classes available in the Android SDK: Frame Layout — the simplest of the Layout Managers, the Frame Layout pins each child view within its frame. The default position is the top-left corner, though you can use the gravity attribute to alter its location. Adding multiple children stacks each new child on top of the one before, with each new View potentially obscuring the previous ones. Linear Layout — a Linear Layout aligns each child View in either a vertical or a horizontal line. A vertical layout has a column of Views, whereas a horizontal layout has a row of Views. The Linear Layout supports a weight attribute for each child View that can control the relative size of each child View within the available space. Relative Layout — One of the most flexible of the native layouts, the Relative Layout lets you define the positions of each child View relative to the others and to the screen boundaries. GridLayout — Introduced in Android 4.0 (API level 14), the Grid Layout uses a rectangular grid of infinitely thin lines to lay out Views in a series of rows and columns. The Grid Layout is incredibly flexible and can be used to greatly simplify layouts and reduce or eliminate the complex nesting often required to construct UIs using the layouts described above. Its good practice to use the Layout Editor to construct your Grid Layouts rather than relying on tweaking the XML manually. Each of these layouts is designed to scale to suit the host device’s screen size by avoiding the use of absolute positions or predetermined pixel values. This makes them particularly useful when designing applications that work well on a diverse set of Android hardware. The Android documentation describes the features and properties of each layout class in detail; so, rather than repeat that information here, I’ll refer you to http://developer.android.com/guide/ topics/UI/layout-objects.html. You’ll see practical example of how these layouts should be used as they’re introduced in the examples throughout this book. Later in this chapter you’ll also learn how to create compound controls by using and/or extending these layout classes. Defining Layouts The preferred way to define a layout is by using XML external resources. Each layout XML must contain a single root element. This root node can contain as many nested layouts and Views as necessary to construct an arbitrarily complex UI. For each of the layout elements, the constants wrap content and match parent are used rather than an exact height or width in pixels. These constants, combined with layouts that scale offer the simplest, and most powerful, technique for ensuring your layouts are screen-size and resolution independent. 94 CU IDOL SELF LEARNING MATERIAL (SLM)
The wrap content constant sets the size of a View to the minimum required to contain the contents it displays (such as the height required displaying a wrapped text string). The match parent constant expands the View to match the available space within the parent View, Fragment, or Activity. Later in this chapter you’ll learn how to set the minimum height and width for your own controls, as well as further best practices for resolution independence. Implementing layouts in XML decouples the presentation layer from the View, Fragment, and Activity controller code and business logic. It also lets you create hardware configuration specific variations that are dynamically loaded without requiring code changes. Using Layouts to Create Device Independent User Interfaces A defining feature of the layout classes described previously, and the techniques described for using them within your apps, is their ability to scale and adapt to a wide range of screen sizes, resolutions, and orientations. The variety of Android devices is a critical part of its success. For developers, this diversity introduces a challenge for designing UIs to ensure that they provide the best possible experience for users, regardless of which Android device they own. 5.3.1 Linear Layout The Linear Layout is one of the simplest layout classes. It allows you to create simple UIs (or UI elements) that align a sequence of child Views in either a vertical or a horizontal line. The simplicity of the Linear Layout makes it easy to use but limits its flexibility. In most cases you will use Linear Layouts to construct UI elements that will be nested within other layouts, such as the Relative Layout. Listing 4-1 shows two nested Linear Layouts a horizontal layout of two equally sized buttons within a vertical layout that places the buttons above a List View. 5.3.2 Relative Layout The Relative Layout provides a great deal of flexibility for your layouts, allowing you to define the position of each element within the layout in terms of its parent and the other Views. Listing 4-2 modifies the layout described in Listing 4-1 to move the buttons below the List View theRelative Layout enables you to specify how child views are positioned relative to each other. XML UI creates the screen 5.3.3 Constraint Layout A Constraint Layout is a View Group which allows you to position and size widgets in a flexible way. 95 CU IDOL SELF LEARNING MATERIAL (SLM)
Note: Constraint Layout is available as a support library that you can use on Android systems starting with API level 9. As such, we are planning on enriching its API and capabilities over time. This documentation will reflect those changes. There are currently various types of constraints that you can use: Relative positioning Margins Cantering positioning Circular positioning Visibility behaviour Dimension constraints Chains Virtual Helpers objects Optimizer Note that you cannot have a circular dependency in constraints. Also see Constraint Layout. Layout Prams for layout attributes 5.4 UI CONTROLS In the previous chapter, you learned about the various layouts that you can use to position your views in an activity. You also learned about the techniques you can use to adapt to different screen resolutions and sizes. In this chapter, you will look at the various views that you can use to design the user interface for your applications. You will learn about the following View Groups: Basic views — Commonly used views such as the TextView, EditText, and Button views Picker views — Views that enable users to select from a list, such as the TimePicker and DatePicker views List views — Views that display a long list of items, such as the ListView and the Spinner View views Specialized fragments — Special fragments that perform specific functions Subsequent chapters cover the other views not covered in this chapter, such as the analogue and digital clock views and other views for displaying graphics, and so on. 5.4.1 Text View 96 CU IDOL SELF LEARNING MATERIAL (SLM)
When you create a new Android project, Eclipse always creates the main.xml fi le (located in the res/layout folder), which contains a <Text View> element: <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” Android layout_width=”fill_parent” Android layout_height=”fill_parent” Android orientation=”vertical” > <TextView Android layout_width=”fill_parent” Android layout_height=”wrap_content” Android text=”@string/hello” /> </LinearLayout> The TextView is used to display text to the user. This is the most basic view and one that you will frequently use when you develop Android applications. If you need to allow users to edit the text displayed, you should use the subclass of Text View, EditText, which is discussed in the next section. In Android, TextView displays text to the user and optionally allows them to edit it programmatically. TextView is a complete text editor, however basic class is configured to not allow editing but we can edit it. Figure 5.1: Text view View is the parent class of TextView. Being a subclass of view the text view component can be used in your app’s GUI inside a ViewGroup, or as the content view of an activity. We can create a TextView instance by declaring it inside a layoutor by instantiating it programmatically. Android text attribute holds the string that’s to be displayed. 97 CU IDOL SELF LEARNING MATERIAL (SLM)
Android id attribute stores the unique identifier of the TextView. We retrieve the TextView in our Java Activity using this id. In the respective activity/fragment, we call the above TextView using findViewById TextView textView = findView By Id In the present Android SDK versions, the type TextView is inferred on the right-hand side. In Android SDK < 25, we must explicitly cast the findViewById to Ideally, instead of hardcoding the string in the above xml code, we should set it in the strings.xml file and use it as: android text=\"@string/app_name\" Important Attributes of TextView Some commonly used attributes of a TextView are listed below. Android text Colour: To set the colour of the text. Can be set as #rgb #rrggbb #aarrggbb aa represents the transparency, opacity. We can also set the colour from colors.xml. Example: @colour/colourPrimary Dark or @android colour/white Android textSize: To set the size of the textView. Generally, it’s set in sp (scaled pixels). Example: 18sp. Android textAllCaps: Set the Boolean value. Setting true would capitalize the string. Android textStyle: By default, the style is normal. You can set it to bold, italic. To set one or more together use. Android max Lines: Set the maximum number of lines you want the text to be in. Setting this to 1 would make it a single line TextView. Android ellipses: This is used for truncating the text which is longer than the view rather than being broken. Start adds In place of the starting characters of the string end adds them for the remaining characters. Middle adds it for the middle ones. Setting marquee makes the textview slide left right continuously. For marquee to work, set android textIsSelected \"true\" and android scroll Horizontally \"true\" Android gravity: Specifies the alignment of the text by the view’s x- and/or y-axis when the string is smaller than the TextView width/height. Android lineSpacingMultiplier: Extra spacing between lines of text, as a multiplier. Setting 1.5 makes the spacing 1.5 times larger than the current spacing. Android text Appearance: Sets a style for the text which includes its own colour, size, font etc. We can use built-in styles or create our own in the styles.xml file. Android typeface: is used to set the typeface of the text among mono space, serif, sans, normal. 98 CU IDOL SELF LEARNING MATERIAL (SLM)
Android visibility: is used to set the visibility of the TextView among visible, invisible, gone. gone is different from invisible gone makes the TextView indivisible and makes it vanish from the layout. In invisible the TextView is still at the same place. 5.4.2 Edit Text, An EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of TextView that includes rich editing capabilities. EditText Attributes Following are the important attributes related to EditText control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from Android Widget TextView Class Sr. No Attribute & Description 1 android:autoText If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. 2 android: draw able Bottom This is the draw able to be drawn below the text. 3 android: draw able Right This is the draw able to be drawn to the right of the text. 4 Android editable If set, specifies that this TextView has an input method. 5 Android text 99 CU IDOL SELF LEARNING MATERIAL (SLM)
This is the Text to display. Table 5.1: EditText Attributes 1 Inherited from android view Sr. No Attribute & Description 1 android: background This is a draw able to use as the background. 2 android:contentDescription This defines text that briefly describes content of the view. 3 android:id This supplies an identifier name for this view. 4 android:onClick This is the name of the method in this View's context to invoke when the view is clicked. 5 android:visibility This controls the initial visibility of the view. Table 5.2: EditText Attributes 2 Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and EditText. 100 CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270