PPT Companion to Android


Published on

A complete power point presentation on Android.
(favorite the presentation if you like it !)

Published in: Technology

PPT Companion to Android

  1. 2. Few reasons to go MAD… <ul><li>Smart Phones </li></ul><ul><ul><li>Internet access anywhere </li></ul></ul><ul><ul><li>Social networking </li></ul></ul><ul><li>Millions of mobile users </li></ul><ul><li>Open standards </li></ul>
  2. 3. Introduction to Android <ul><li>Open software platform for mobile development. </li></ul><ul><li>A complete stack – OS, Middleware, Applications. </li></ul><ul><li>An Open Handset Alliance (OHA) project. </li></ul><ul><li>Powered by Linux operating system. </li></ul><ul><li>Fast application development in Java. </li></ul><ul><li>Open source under the Apache license </li></ul>
  3. 4. Why Android <ul><li>Android was designed as a platform for software development. </li></ul><ul><li>Android is open . </li></ul><ul><li>Android is free. </li></ul><ul><li>Community support. </li></ul><ul><li>Tool support. </li></ul>
  4. 5. Open Handset Alliance (OHA) <ul><li>The OHA is a group of hardware and software developers, including Google, NTT DoCoMo, Sprint Nextel, and HTC … </li></ul><ul><li>Goal </li></ul><ul><ul><li>Accelerate innovation in mobile </li></ul></ul><ul><ul><li>Offer consumers a richer, less expensive, and better mobile experience </li></ul></ul><ul><li>OHA have developed Android™, the first complete, open, and free mobile platform </li></ul>
  5. 7. Features <ul><li>Application framework enabling reuse and replacement of components </li></ul><ul><li>Dalvik virtual machine optimized for mobile devices </li></ul><ul><li>Integrated browser based on the open source WebKit engine </li></ul><ul><li>Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) </li></ul><ul><li>SQLite for structured data storage </li></ul><ul><li>Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) </li></ul>
  6. 8. Features (Contd….) <ul><li>GSM Telephony (hardware dependent) </li></ul><ul><li>Bluetooth, EDGE, 3G, and WiFi (hardware dependent) </li></ul><ul><li>Camera, GPS, compass, and accelerometer (hardware dependent) </li></ul><ul><li>Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE </li></ul>
  7. 9. Android Architecture
  8. 10. Linux Kernel <ul><li>Android relies on Linux version 2.6 for core system services such as device drivers, security, memory management ,process management. </li></ul><ul><li>The kernel also acts as an abstraction layer between the hardware and the rest of the software stack. </li></ul>
  9. 11. <ul><li>Includes a set of C/C++ libraries. </li></ul><ul><li>Interface through Java. </li></ul><ul><li>Surface manager – Handling UI Windows. </li></ul><ul><li>2D and 3D graphics. </li></ul><ul><li>Media codecs, SQLite, Browser engine. </li></ul>
  10. 12. <ul><li>Dalvik VM (translator between the application side and the operating system) </li></ul><ul><ul><li>Dex files (.dex)format </li></ul></ul><ul><ul><li>Compact and efficient than class files </li></ul></ul><ul><ul><li>Limited memory and battery power </li></ul></ul><ul><li>Core Libraries </li></ul><ul><ul><li>Java 5 Std edition </li></ul></ul><ul><ul><li>Collections, I/O etc… </li></ul></ul>
  11. 13. Application Framework <ul><li>Framework elements are: Intents , Content Providers , Views and managers </li></ul><ul><li>This layer has been designed to facilitate the reuse of components in android </li></ul><ul><li>Developers can build their applications to execute on android kernel and inter-operate among themselves and with existing applications </li></ul>
  12. 14. Applications <ul><li>Android will ship with a set of core applications including an </li></ul><ul><li>a)Email client, </li></ul><ul><li>b)SMS program, </li></ul><ul><li>c)Calendar, </li></ul><ul><li>d)Contacts & others…. </li></ul><ul><li>All the applications are written using the Java programming language. </li></ul>
  13. 15. Android applications are compiled to Dalvik byte code Write app in Java Compiled in Java Transformed to Dalvik byte code Linux OS Loaded into Dalvik VM
  14. 16. Android SDK  ADT: Android Development Tool, an Eclipe plugin  Two debuggers  adb : Android Debug Bridge  ddms : Dalvik Debug Monitor Server  aapk : Android Application package tool  All resources are bundled into an archive, called apk file.  dx : java byte code to Dalvik executable translator
  15. 17. Differences between Smart Phones Feature Android Windows mobile BlackBerry company Google Microsoft RIM OS family Linux Windows Mobile OS Languages Java Visual C++ C++ SDK Platform Multiplatform dependent dependent Face book Yes Yes Yes Multitasking Yes limited limited
  16. 18. Differences between Apple and Android Specification Apple Android Ownership Apple Proprietary Google open Source Compatible Access Technology 3G,3.5G,Wi-Fi,Bluetooth 2G,3G,3.5G and 4G(GSM , CDMA,Bluetooth,Wi-Fi, and WiMAX) Compatible Devices iPod , iPod Touch, iPhones Any Devices Messaging SMS , MMS ,email SMS , MMS , email and C2DM Web Browser Safari Open source Web kit layout engine coupled with Chrome’s V8 JavaScript engine Connectivity Wi-Fi, Bluetooth Wi-Fi, Bluetooth and NFC Multitasking Supported Supported Other device connectivity (Internet) Bluetooth (Internet Tethering) Hotspot feature with Wi-Fi
  17. 19. Differences between Apple and Android Specification Apple Android Chrome to phone Not supported Supported 3D Google Map Not Yet Supported Email Attachments Single file only Multiple files Google Talk Web browser chat GTalk Specific Client and Video Supported Hardware Vendors Apple Samsung,Motorola,LG,Sony Ericsson, Dell,Huawei,HTC 3rd Party Branded OS No Supported Adobe Flash Support Not Supported Supported
  18. 20. Android applications have common structure Views such as lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data A Resource Manager , providing access to non-code resources such as localized strings, graphics, and layout files A Notification Manager that enables all apps to display custom alerts in the status bar An Activity Manager that manages the life cycle of applications and provides a common navigation backstack
  19. 21. Android applications have common structure Broadcast receivers can trigger intents that start an application Data storage provide data for your apps, and can be shared between apps – database, file, and shared preferences (hash map) used by group of applications Services run in the background and have no UI for the user – they will update data, and trigger events Intents specify what specific action should be performed Activity is the presentation layer of your app: there will be one per screen, and the Views provide the UI to the activity
  20. 22. Replacing & Reusing Components GMail Contacts Home Blogger Chat Client component makes a request for a specific action “ Pick photo” Picasa System picks best component for that action New components can use existing functionality Blogger Photo Gallery
  21. 23. There is a common file structure for applications code images files UI layouts constants Autogenerated resource list
  22. 24. Hello World !!! <ul><li>1. Create a new Android Project </li></ul><ul><ul><li>Select File > New > Android Project </li></ul></ul><ul><li>2. Fill out the project details </li></ul><ul><ul><li>Enter HelloWorld for Project Name </li></ul></ul><ul><ul><li>Select “ Create new project in workspace ” </li></ul></ul><ul><ul><li>Enter HelloWorld in App name. </li></ul></ul><ul><ul><li>Enter com.enlume.HelloWorld in Package Name </li></ul></ul><ul><ul><li>Enter HelloWorld in Activity name (and yes we want to create an Activity) </li></ul></ul>
  23. 25. Project Properties Project Name This is the name of the directory or folder on your computer that you want to contain the project. Package Name This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated. The package name you use in your application must be unique across all packages installed on the system; for this reason, it's very important to use a standard domain-style package for your applications. In the example above, we used the package domain &quot;com.chicagoandroids&quot;. Activity Name This is the name for the class stub that will be generated by the plug-in. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. Application Name This is the human-readable title for your application.
  24. 26. The Automatic* Portions… <ul><li>Left: Manifest (* not that automatic) </li></ul><ul><li>Right: R class and the android library (no need to touch) </li></ul>
  25. 27. The Automatic* Portions… <ul><li>Left: Source directories, where your classes go… </li></ul><ul><li>Right: Resources (this is what gets automatically build into the R class) </li></ul>
  26. 28. A word about the emulator <ul><li>You can create different Run configurations for different target devices. </li></ul><ul><li>It is possible to target different resolutions (HVGA, HVGA-P, HVGA-L, etc) </li></ul><ul><li>Network speed and latency, etc. </li></ul><ul><li>Use the AVD manager and the ‘Run->Run configurations’ to manipulate </li></ul>
  27. 29. Run hello world <ul><li>Select the root of the project. </li></ul><ul><li>Click in the ‘green play icon’. </li></ul><ul><li>Pick Android Project </li></ul><ul><li>That will get the emulator going… </li></ul>
  28. 30. The AndroidManifest lists application details <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> </li></ul><ul><li><manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; </li></ul><ul><li>package=&quot;com.my_domain.app.helloactivity&quot;> </li></ul><ul><li><application android:label=&quot;@string/app_name&quot;> </li></ul><ul><li><activity android:name=&quot;.HelloActivity&quot;> </li></ul><ul><li><intent-filter> </li></ul><ul><li><action android:name=&quot;android.intent.action.MAIN&quot;/> </li></ul><ul><li><category android:name=&quot;android.intent.category.LAUNCHER&quot;/> </li></ul><ul><li></intent-filter> </li></ul><ul><li></activity> </li></ul><ul><li></application> </li></ul>
  29. 31. The AndroidManifest File <ul><li>This file must declare all activities, services, broadcast receivers and content provider of the application. </li></ul><ul><li>It must also contain the required permissions for the application. For example if the application requires network access it must be specified here </li></ul><ul><li>It can be thought as the deployment descriptor for an Android application. </li></ul><ul><li>The &quot;package&quot; attribute defines the base package for the following Java elements </li></ul>
  30. 32. The AndroidManifest File <ul><li>&quot;android:versionName&quot; and &quot;android:versionCode&quot; specify the version of your application. </li></ul><ul><li>intent filter registered defines that this activity is started once the application starts (action android:name=&quot;android.intent.action.MAIN&quot;). </li></ul><ul><li>The category definition (category android:name=&quot;android.intent.category.LAUNCHER&quot; ) defines that this application is added to the application directory on the Android device. </li></ul><ul><li>The &quot;uses-sdk&quot; part defines the minimal SDK version your application is valid for. </li></ul>
  31. 33. Activities and Tasks <ul><li>An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. </li></ul><ul><li>Each activity is given a window in which to draw its user interface. </li></ul><ul><li>An application usually consists of multiple activities that are loosely bound to each other. </li></ul>
  32. 34. Activities (continue)
  33. 35. Activities (continue)
  34. 36. Activities vs Tasks (Apps) <ul><li>A concrete class in the API </li></ul><ul><li>An encapsulation of a particular operation </li></ul><ul><li>They run in the process of the .APK which installed them </li></ul><ul><li>Optionally associated with a window (UI) </li></ul><ul><li>An execution Context </li></ul><ul><li>More of a notion than a concrete API entity </li></ul><ul><li>A collection of related Activities </li></ul><ul><li>Capable of spanning multiple processes </li></ul><ul><li>Associated with their own UI history stack </li></ul><ul><li>What users on other platforms know as “applications” </li></ul>
  35. 37. Activities and Tasks (Cont) <ul><li>Tasks (Cont) </li></ul><ul><ul><li>All activities in a task are arranged in a stack. </li></ul></ul><ul><ul><li>If one activity starts another, the new activity is pushed on the stack and it becomes the running activity. </li></ul></ul><ul><ul><li>When the user presses the BACK key, the current activity is popped from the stack and the previous one resumes. </li></ul></ul>
  36. 38. Managing Tasks <ul><li>Android manages tasks and the back stack by placing all activities started in succession in the same task and in a &quot;last in, first out&quot; stack. </li></ul><ul><li>You might decide that you want to interrupt the normal behavior. </li></ul><ul><ul><li>Perhaps you want an activity in your application to begin a new task when it is started (instead of being placed within the current task). </li></ul></ul><ul><ul><li>when you start an activity, you want to bring forward an existing instance of it (instead of creating a new instance on top of the back stack). </li></ul></ul><ul><ul><li>you want your back stack to be cleared of all activities start an activity except for the root activity when the user leaves the task. </li></ul></ul>
  37. 39. Managing Tasks <ul><li>You can do these things and more, with attributes in the <activity> manifest element and with flags in the intent that you pass to startActivity(). </li></ul><ul><li><activity> attributes you can use are: </li></ul><ul><ul><li>taskAffinity </li></ul></ul><ul><ul><li>launchMode </li></ul></ul><ul><ul><li>allowTaskReparenting </li></ul></ul><ul><ul><li>clearTaskOnLaunch </li></ul></ul><ul><ul><li>alwaysRetainTaskState </li></ul></ul><ul><ul><li>finishOnTaskLaunch </li></ul></ul><ul><li>And the principal intent flags you can use are: </li></ul><ul><ul><li>FLAG_ACTIVITY_NEW_TASK </li></ul></ul><ul><ul><li>FLAG_ACTIVITY_CLEAR_TOP </li></ul></ul><ul><ul><li>FLAG_ACTIVITY_SINGLE_TOP </li></ul></ul>
  38. 40. Activities and Tasks (Cont) <ul><li>Launch modes allow you to define how a new instance of an activity is associated with the current task </li></ul><ul><ul><li>There are four launch modes: </li></ul></ul><ul><li>standard (default) / singleTop / singleTask / singleInstance </li></ul><ul><ul><li>A launch mode can be set for each activity: </li></ul></ul>
  39. 41. Activities and Tasks (Cont) <ul><li>Launch Modes (Cont) </li></ul><ul><ul><li>The modes differ from each other on four points: </li></ul></ul><ul><ul><ul><li>Which task will hold the activity that responds to the intent </li></ul></ul></ul>New Activity Activity A Root Activity Original Task Activity A Root Activity Original Task New Activity New Task standard/singleTop without FLAG_ACTIVITY_NEW_TASK singleTask/singleInstance
  40. 42. Activities and Tasks (Cont) <ul><li>Launch Modes (Cont) </li></ul><ul><ul><li>The modes differ from each other on four points: (Cont) </li></ul></ul><ul><ul><ul><li>Whether there can be multiple instances of the activity </li></ul></ul></ul><ul><ul><ul><ul><li>A &quot;standard&quot; or &quot;singleTop&quot; activity can be instantiated many times. </li></ul></ul></ul></ul><ul><ul><ul><ul><li>A &quot;singleTask&quot; or &quot;singleInstance&quot; activity is limited to just one instance. </li></ul></ul></ul></ul>Activity B Activity A Task A Activity D Task B Activity B and Activity C are standard/singleTop Activity C Activity B Activity C Activity B Activity A Task A Activity C Task B Activity C is singleTask or singleInstance
  41. 43. Activities and Tasks (Cont) <ul><li>Launch Modes (Cont) </li></ul><ul><ul><li>The modes differ from each other on four points: (Cont) </li></ul></ul><ul><ul><ul><li>Whether the instance can have other activities in its task </li></ul></ul></ul>&quot;standard&quot; <ul><li>These modes permit multiple activities to belong to the task. </li></ul><ul><li>A &quot;singleTask&quot; activity will always be the root activity of the task. </li></ul>&quot;singleTop&quot; &quot;singleTask&quot; &quot;singleInstance&quot; <ul><li>An activity stands alone as the only activity in its task. </li></ul>
  42. 44. Activities and Tasks (Cont) <ul><li>Launch Modes (Cont) </li></ul><ul><ul><li>The modes differ from each other on four points: (Cont) </li></ul></ul><ul><ul><ul><li>Whether a new instance of the class will be launched to handle a new intent </li></ul></ul></ul>Activity B Activity A Activity C Original Task Activity D An intent arrives for an activity of type D Activity B Activity A Activity C Activity D Activity D If D is&quot;standard&quot; Activity B Activity C Activity D If D is&quot;singleTop&quot; The existing instance D is expected to handle the new intent (since it's at the top of the stack) Activity A
  43. 45. Activities and Tasks (Cont) <ul><li>Launch Modes (Cont) </li></ul><ul><ul><li>The modes differ from each other on four points: (Cont) </li></ul></ul><ul><ul><ul><li>Whether a new instance of the class will be launched to handle a new intent (Cont) </li></ul></ul></ul>Activity B Original Task An intent arrives for an activity of type B If B is&quot;singleInstance&quot; A &quot;singleInstance&quot; activity is always at the top of the stack, so it is always in position to handle the intent. Activity B
  44. 46. Activities and Tasks (Cont) <ul><li>Launch Modes (Cont) </li></ul><ul><ul><li>The modes differ from each other on four points: (Cont) </li></ul></ul><ul><ul><ul><li>Whether a new instance of the class will be launched to handle a new intent (Cont) </li></ul></ul></ul>Activity B Original Task An intent arrives for an activity of type B If B is&quot;singleTask&quot; Activity B can handle the intent since it is in position. Activity B Activity A Activity A Activity B Original Task An intent arrives for an activity of type B If B is&quot;singleTask&quot; Activity B cannot handle the intent since it is not in position and the intent is dropped. Activity B Activity A Activity A
  45. 47. Activities and Tasks (Cont)
  46. 48. Activities and Tasks (Cont) <ul><li>Using Intent Flags : </li></ul><ul><ul><li>FLAG_ACTIVITY_NEW_TASK :Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent(). </li></ul></ul><ul><ul><li>FLAG_ACTIVITY_SINGLE_TOP: If the activity being started is the current activity (at the top of the back stack), then the existing instance receives a call to onNewIntent(), instead of creating a new instance of the activity. </li></ul></ul><ul><ul><li>FLAG_ACTIVITY_NO_HISTORY : This flag implies that the called activity is not kept in the task’s stack. When navigating away, the user cannot return to it. </li></ul></ul><ul><ul><li>FLAG_ACTIVITY_CLEAR_TOP If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()). </li></ul></ul>
  47. 49. Activities and Tasks (Cont) <ul><li>Affinities </li></ul><ul><ul><li>An affinity means a preference for each activity to belong to a certain task. </li></ul></ul><ul><ul><li>An individual affinity can be set for each activity: </li></ul></ul><ul><ul><li>By default, a new activity is launched into the task of the activity that called startActivity(). </li></ul></ul>
  48. 50. Activities and Tasks (Cont) <ul><li>Affinities (Cont) </li></ul><ul><ul><li>Two circumstances where the affinity comes into play: </li></ul></ul><ul><ul><ul><li>FLAG_ACTIVITY_NEW_TASK flag </li></ul></ul></ul><ul><li>If the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. </li></ul><ul><ul><ul><ul><li>If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. </li></ul></ul></ul></ul><ul><ul><ul><ul><li>If not, it begins a new task. </li></ul></ul></ul></ul><ul><ul><li>allowTaskReparenting attribute </li></ul></ul><ul><li>If an activity has its allowTaskReparenting attribute set to &quot;true&quot;, it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. </li></ul>
  49. 51. Activities and Tasks (Cont) <ul><li>Clearing the Stack </li></ul><ul><ul><li>Default Control </li></ul></ul><ul><li> If the user leaves a task for a long time, the system clears the task of all activities except the root activity. </li></ul><ul><ul><li>Some activity attributes that can be used to modify the default control: </li></ul></ul><ul><ul><ul><li>If alwaysRetainTaskState is set to the root activity of a task </li></ul></ul></ul><ul><ul><ul><ul><li>The task retains all activities in its stack even after a long period. </li></ul></ul></ul></ul><ul><ul><ul><li>If clearTaskOnLaunch is set to the root activity of a task </li></ul></ul></ul><ul><ul><ul><ul><li>The stack is cleared down to the root activity whenever the user leaves the task and returns to it. </li></ul></ul></ul></ul><ul><ul><ul><ul><li>The user always returns to the task in its initial state, even after a momentary absence. </li></ul></ul></ul></ul>
  50. 52. Activities and Tasks (Cont) <ul><li>Clearing the Stack (Cont) </li></ul><ul><ul><li>Some activity attributes that can be used to modify the default control: (Cont) </li></ul></ul><ul><ul><ul><li>If finishOnTaskLaunch is set to an activity of a task </li></ul></ul></ul><ul><ul><ul><ul><li>- The activity remains part of the task only for the current session. </li></ul></ul></ul></ul><ul><ul><ul><ul><li>- If the user leaves and then returns to the task, it no longer is present. </li></ul></ul></ul></ul><ul><ul><li>Another way to force activities to be removed from the stack ( FLAG_ACTIVITY_CLEAR_TOP flag): </li></ul></ul><ul><ul><ul><li>If an intent includes the FLAG_ACTIVITY_CLEAR_TOP flag and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away. </li></ul></ul></ul>
  51. 53. Process Basics <ul><li>How does it all of this relate to the Unix roots of Android? </li></ul><ul><ul><li>Android process == Linux process (w/ its own unique UID) </li></ul></ul><ul><ul><li>By default, 1 process per APK </li></ul></ul><ul><ul><li>By default, 1 thread per process </li></ul></ul><ul><ul><li>Most components interleave events into the main thread </li></ul></ul>
  52. 54. Creating an Activity <ul><li>To create an activity, you must create a subclass of Activity . </li></ul><ul><li>In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle. </li></ul><ul><li>The two most important callback methods are: </li></ul><ul><ul><li>onCreate() </li></ul></ul><ul><ul><li>onPause(). </li></ul></ul>
  53. 55. Declaring the Activity in Manifest File <ul><li>You must declare your activity in the manifest file in order for it to be accessible to the system. </li></ul><ul><li><manifest ... >   <application ... >       <activity android:name=&quot;.ExampleActivity&quot; />       ...   </application ... >   ... </manifest > </li></ul><ul><li>There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI </li></ul>
  54. 56. Declaring the Activity in Manifest File <ul><li>The android:name attribute is the only required attribute—it specifies the class name of the activity . </li></ul><ul><li>Using IntentFilters </li></ul><ul><ul><li>An <activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it. </li></ul></ul><ul><ul><li>When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the &quot;main&quot; action and should be placed in the &quot;launcher&quot; category. </li></ul></ul><ul><ul><li>if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity </li></ul></ul>
  55. 57. Starting an Activity <ul><li>You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. </li></ul><ul><li>The intent specifies either the exact activity you want to start or describes the type of action you want to perform. </li></ul><ul><li>An intent can also carry small amounts of data to be used by the activity that is started </li></ul>
  56. 58. Starting an Activity <ul><li>Intent Examples : </li></ul><ul><ul><li>Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); </li></ul></ul><ul><ul><li>Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent); </li></ul></ul><ul><li>Starting an activity for a result </li></ul><ul><ul><li>Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult() (instead of startActivity()) </li></ul></ul><ul><ul><li>To then receive the result from the subsequent activity, implement the onActivityResult() callback method. </li></ul></ul><ul><ul><li>When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method. </li></ul></ul>
  57. 59. Managing the Activity Lifecycle <ul><li>An activity can exist in essentially three states: </li></ul><ul><ul><li>Resumed :The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as &quot;running&quot;.) </li></ul></ul><ul><ul><li>Paused: Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. </li></ul></ul><ul><ul><li>Stopped : The activity is completely obscured by another activity </li></ul></ul>
  58. 60. Paused v/s Stopped <ul><li>A paused activity is completely alive </li></ul><ul><li>The Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager </li></ul><ul><li>It can be killed by the system in extremely low memory situations. </li></ul><ul><li>A stopped activity is also still alive. </li></ul><ul><li>The Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager. </li></ul><ul><li>It is no longer visible to the user and it can be killed by the system when memory is needed elsewhere. </li></ul>
  59. 61. Android Activity Life Cycle <ul><li>Activities have several states </li></ul><ul><li>Lifecycle methods are called on transitions </li></ul><ul><li>You typically don’t need to use them all, but they are there </li></ul>
  60. 62. Android Activity Life Cycle <ul><li>@override these methods in your Activity class, and Android will call them at the appropriate time </li></ul><ul><li>onCreate(Bundle): This is called when the 1st Activity Startsup </li></ul><ul><li>onStart(): Called just before the activity becomes visible to the user </li></ul><ul><li>onResume(): Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack </li></ul>
  61. 63. Android Activity Life Cycle <ul><li>onPause(): Called when the system is about to start resuming another activity </li></ul><ul><li>onStop(): This is called when the activity is no longer visible to the user </li></ul><ul><li>onDestroy(): Called before the activity is destroyed. It could be called either because the activity is finishing or because the system is temporarily destroying this instance of the activity to save space </li></ul>
  62. 64. Saving Activity State <ul><li>When an activity is paused or stopped, the state of the activity is retained. </li></ul><ul><li>Any changes the user made within the activity are retained in memory, so that when the activity returns to the foreground (when it &quot;resumes&quot;), those changes are still there. </li></ul><ul><li>When the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact. </li></ul>
  63. 65. Saving Activity State <ul><li>The system must recreate the Activity object if the user navigates back to it and important information about the activity state is preserved by implementing an additional callback method </li></ul><ul><li>The callback method in which you can save information about the current state of your activity is onSaveInstanceState(). </li></ul><ul><li>The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle object </li></ul>
  64. 66. Tasks and Back Stack <ul><li>A task is a collection of activities that users interact with when performing a certain job. </li></ul><ul><li>The activities are arranged in a stack (the &quot;back stack&quot;), in the order in which each activity is opened. </li></ul><ul><li>When the current activity starts another, the new activity is pushed on the top of the stack and takes focus. </li></ul><ul><li>When the user presses the BACK key, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored) </li></ul>
  65. 67. Tasks and Back Stack
  66. 68. Application Life Cycle <ul><li>Applications run in their own process . </li></ul><ul><li>Process are started and stopped as needed to run an application’s component. </li></ul><ul><li>Process may be killed to reclaim resources . </li></ul>
  67. 69. Application Life Cycle (1) System Process Home Process Home Mail Message Browser Map Mail Process Browser Process Map Process
  68. 70. Application Life Cycle (2) System Process Home Process Home Map Browser Message Mail Map Process Browser Process Mail Process
  69. 71. Intents & Intent Filters
  70. 72. What is Intent Messaging? <ul><li>Three of the core components of an Android application - activities, services, and broadcast receivers - are activated through messages, called intents </li></ul><ul><li>One activity starts another activity by creating/sending an Intent </li></ul><ul><li>Means of leveraging activities, services, and broadcast receivers of other applications </li></ul><ul><li>Application #1 can use “Photo display” activity of Application #2 (or system) by creating/sending an intent </li></ul>
  71. 73. What is Intent Messaging? <ul><li>An Intent object is passed to startActivity() or startActivityForResult() to launch an activity or get an existing activity to do something new </li></ul><ul><li>An Intent object is passed to startService() to initiate a service or deliver new instructions to an ongoing service. </li></ul><ul><li>Intent objects passed to any of the broadcast methods </li></ul>
  72. 74. What is Intent Messaging? <ul><li>Intent messaging is a facility for late run-time binding between components in the same or different applications. </li></ul><ul><li>Enables a flexible and agile architecture: A component that performs a task is selected during runtime </li></ul><ul><li>One activity can start another activity by creating an intent that says “Display web browser” - Android runtime then selects a best qualified “Display web browser” activity among the possible candidates during runtime through so-called “Intent resolution” </li></ul>
  73. 75. What Does Intent Object Contain? <ul><li>Information of interest to the target component that receives the intent </li></ul><ul><ul><li>Action to be taken </li></ul></ul><ul><ul><li>Data to act on </li></ul></ul><ul><li>Information of interest to the Android system </li></ul><ul><ul><li>Category of component that should handle the intent </li></ul></ul><ul><ul><li>Instructions on how to launch a target activity </li></ul></ul>
  74. 76. Intent Object Structure
  75. 77. Intent Object Structure Is Made Of <ul><li>Component name </li></ul><ul><li>Action </li></ul><ul><li>Data </li></ul><ul><li>Category </li></ul><ul><li>Extras </li></ul><ul><li>Flags </li></ul>
  76. 78. Component name Field <ul><li>Specifies the name of the component (name of the activity if the component is activity) that should handle the intent </li></ul><ul><ul><li>Class name of the target component (for example &quot; com.enlume.ForwardTargetActivity&quot;) </li></ul></ul><ul><li>Setting component name is optional </li></ul><ul><ul><li>If it is set, the Intent object is delivered to an instance of the designated class. </li></ul></ul><ul><ul><li>If it is not set, Android uses other information in the Intent object to locate a suitable target - this is called “intent resolution” </li></ul></ul>
  77. 79. Action Field <ul><li>A string naming the action to be performed </li></ul><ul><li>The Intent class defines a number of predefined action constants, including </li></ul><ul><ul><li>ACTION_CALL, ACTION_EDIT, ACTION_MAIN, ACTION_SYNC, ACTION_BATTERY_LOW, etc. </li></ul></ul><ul><li>You can also define your own action strings for activating the components in your application </li></ul><ul><li>The action largely determines how the rest of the intent is structured - particularly the data and e xtras fields - much as a method name determines a set of arguments and a return value. </li></ul>
  78. 80. Data Field <ul><li>The URI of the data to be acted on and the MIME type of that data. </li></ul><ul><li>Different actions are paired with different kinds of data specifications. </li></ul><ul><ul><li>If the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing. </li></ul></ul><ul><ul><li>If the action is ACTION_CALL, the data field would be a tel: URI with the number to call. </li></ul></ul><ul><ul><li>If the action is ACTION_VIEW and the data field is an http: URI, the receiving activity would be called upon to download and display whatever data the URI refers to. </li></ul></ul>
  79. 81. Data Field <ul><li>Examples of Action/Data Pairs </li></ul><ul><ul><li>ACTION_VIEW content://contacts/people/1 – Display information about the person whose identifier is &quot;1&quot;. </li></ul></ul><ul><ul><li>ACTION_DIAL content://contacts/people/1 -- Display the phone dialer with the person filled in. </li></ul></ul><ul><ul><li>ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in. </li></ul></ul><ul><ul><li>ACTION_DIAL tel:123 -- Dial the phone dialer with the given number filled in. </li></ul></ul><ul><ul><li>ACTION_EDIT content://contacts/people/1 – Edit information about the person whose identifier is &quot;1&quot;. </li></ul></ul><ul><ul><li>ACTION_VIEW content://contacts/people/ -- Display a list of people, which the user can browse through. This example is a typical top-level entry into the Contacts application, showing you the list of people. </li></ul></ul>
  80. 82. Category Field <ul><li>A string containing additional information about the kind of component (activity, service, or broadcast receiver) that should handle the intent. </li></ul><ul><li>Any number of category descriptions can be placed in an Intent object </li></ul><ul><li>Android provides a set of predefined categories (We will see them in the following slide) </li></ul><ul><li>You can define your own categories </li></ul>
  81. 83. Pre-defined Categories (by Android) <ul><li>CATEGORY_BROWSABLE - The target activity can be invoked within the browser to display data referenced by a link — for example, an image or an e-mail message. </li></ul><ul><li>CATEGORY_HOME - This is the home activity, that is the first activity that is displayed when the device boots. </li></ul><ul><li>CATEGORY_LAUNCHER - The activity can be the initial activity of a task and is listed in the top-level application launcher. </li></ul><ul><li>Many more </li></ul>
  82. 84. Extras Field <ul><li>Key-value pairs for additional information that should be delivered to the component handling the intent. </li></ul><ul><li>Just as some actions are paired with particular kinds of data URIs, some are paired with particular extras. </li></ul><ul><ul><li>ACTION_TIMEZONE_CHANGED action has a &quot;timezone“ extra that identifies the new time zone </li></ul></ul><ul><ul><li>ACTION_HEADSET_PLUG action has a &quot;state&quot; extra indicating whether the headset is now plugged in or unplugged , as well as a &quot;name&quot; extra for the type of headset </li></ul></ul>
  83. 85. Flags Field <ul><li>Flags of various sorts. </li></ul><ul><li>Many instruct the Android system how to launch an activity (for example, which task the activity should belong to) and how to treat it after it's launched (for example, whether it belongs in the list of recent activities). </li></ul>
  84. 86. Intent Resolution
  85. 87. What is Intent Resolution? <ul><li>Android's scheme of determining which target component should be selected for handling a passed intent </li></ul>
  86. 88. Types of Intents <ul><li>Explicit intents </li></ul><ul><ul><li>Designate the target component by its class (the component name field is set by the class name) </li></ul></ul><ul><ul><li>Since component names (class name of the target activity, for example) would generally not be known to developers of other applications, explicit intents are typically used for application-internal messages — such as an activity starting a subordinate service or launching a sister activity. </li></ul></ul><ul><li>Implicit intents </li></ul><ul><ul><li>Do not name a target (the component name field is blank). </li></ul></ul><ul><ul><li>Implicit intents are often used to activate components in other applications. </li></ul></ul>
  87. 89. Intent Resolution Schemes <ul><li>“ Explicit resolution” for Explicit intents </li></ul><ul><ul><li>Android delivers an explicit intent to an instance of the designated target class. </li></ul></ul><ul><ul><li>Nothing in the Intent object other than the component name matters for determining which component should get the intent. </li></ul></ul><ul><li>• “ Implicit” resolution for Implicit intents </li></ul><ul><ul><li>In the absence of a designated target, the Android must find the best component (or components) to handle the intent </li></ul></ul><ul><ul><li>By comparing the contents of the Intent object to intent filters, structures associated with the possible target components that can potentially receive intents - intent filters are specified for each component in the AndroidManifest.xml file </li></ul></ul>
  88. 90. What are Intent Filters? <ul><li>Filters describe and advertise the capabilities of a target component </li></ul><ul><ul><li>Informs the system which implicit intents a component can handle </li></ul></ul><ul><li>If a component does not have any intent filters, it can receive only explicit intents. </li></ul><ul><li>A component with filters can receive both explicit and implicit intents. </li></ul><ul><li>A component has separate filters for each job it can do </li></ul>
  89. 91. Where are Filters Specified? <ul><li>Filters are specified for each component in the AndroidManifest.xml file </li></ul><ul><li><manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; ...> </li></ul><ul><li><application android:icon=&quot;@drawable/app_notes&quot; ... > </li></ul><ul><li><activity android:name=&quot;NoteEditor&quot; </li></ul><ul><li>android:theme=&quot;@android:style/Theme.Light&quot; </li></ul><ul><li>android:label=&quot;@string/title_note&quot; > </li></ul><ul><li><intent-filter android:label=&quot;@string/resolve_edit&quot;> </li></ul><ul><li><action android:name=&quot;android.intent.action.VIEW&quot; /> </li></ul><ul><li><action android:name=&quot;android.intent.action.EDIT&quot; /> </li></ul><ul><li><action android:name=&quot;com.android.notepad.action.EDIT_NOTE&quot; /> </li></ul><ul><li><category android:name=&quot;android.intent.category.DEFAULT&quot; /> </li></ul><ul><li><data android:mimeType=&quot;vnd.android.cursor.item/vnd.google.note&quot; /> </li></ul><ul><li></intent-filter> </li></ul><ul><li><intent-filter> </li></ul><ul><li><action android:name=&quot;android.intent.action.INSERT&quot; /> </li></ul><ul><li><category android:name=&quot;android.intent.category.DEFAULT&quot; /> </li></ul><ul><li><data android:mimeType=&quot;vnd.android.cursor.dir/vnd.google.note&quot; /> </li></ul><ul><li></intent-filter> </li></ul><ul><li></activity> </li></ul><ul><li>... </li></ul>
  90. 92. Intent Filters Intent Resolution
  91. 93. Intent Filters <ul><li>Intent Resolution </li></ul><ul><ul><li>As shown in the previous illustration. Activity3 has issue a generic request for help processing an incoming text‐message. </li></ul></ul><ul><ul><li>Assume the user has installed a “Fancy SMS” application to (perhaps) replace the standard “HUMBLE SMS” app originally included in Android. </li></ul></ul><ul><ul><li>Upon the arrival of the implicit Intent, Android will (somehow) tell the user: You have got a new text‐message. I have a FANCY and a HUMBLE SMS application – which one you want me to execute? Make it a default? </li></ul></ul>
  92. 94. How Android System Perform Intent Resolution (for Implicit Intents)? <ul><li>An implicit Intent object are tested against an intent filters (of target components) in three areas </li></ul><ul><ul><li>Action </li></ul></ul><ul><ul><li>Category </li></ul></ul><ul><ul><li>Data (both URI and data type) </li></ul></ul><ul><li>To be delivered to the target component that owns the filter, it must pass all three tests. </li></ul><ul><li>If an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate. </li></ul><ul><li>If no target can be found, an exception is raised </li></ul>
  93. 95. Action Test <ul><li>To pass this test, the action specified in the Intent object must match one of the actions listed in the filter. </li></ul><ul><li>If the Intent object or the filter does not specify an action, the results are as follows: </li></ul><ul><ul><li>If a filter does not specify any action, there is nothing for an intent to match, so all intents fail the test. No intents can get through the filter. </li></ul></ul><ul><ul><li>On the other hand, an Intent object that doesn't specify an action automatically passes the test — as long as the filter contains at least one action. </li></ul></ul>
  94. 96. Category Test <ul><li>For an intent to pass the category test, every category in the Intent object must match a category in the filter. </li></ul><ul><ul><li>The filter can list additional categories, but it cannot omit any that are in the intent </li></ul></ul><ul><ul><li>The categories of the filter should be the super-set of the categories of the Intent object </li></ul></ul><ul><li>Special case </li></ul><ul><ul><li>An Intent object with no categories should always pass this test, regardless of what's in the filter </li></ul></ul>
  95. 97. Category Test - android.intent.category.DEFAULT <ul><li>Android treats all implicit intents passed to startActivity() as if they contained at least one category: &quot;android.intent.category.DEFAULT“ (the CATEGORY_DEFAULT constant). </li></ul><ul><li>Therefore, activities that are willing to receive implicit intents must include &quot;android.intent.category.DEFAULT&quot; in their intent filters. </li></ul>
  96. 98. Data Test <ul><li>Example </li></ul><ul><li><intent-filter . . . > </li></ul><ul><li><data android:mimeType=&quot;video/mpeg&quot; android:scheme=&quot;http&quot; . . . /> </li></ul><ul><li><data android:mimeType=&quot;audio/mpeg&quot; android:scheme=&quot;http&quot; . . . /> </li></ul><ul><li>. . . </li></ul><ul><li></intent-filter> </li></ul><ul><li>Each <data> element can specify a data type (MIME media type) and URI. </li></ul>
  97. 99. Data Test - URI <ul><li>For each part of the URI, there are separate parts </li></ul><ul><ul><li>scheme, host, port, and path </li></ul></ul><ul><ul><li>scheme://host:port/path </li></ul></ul><ul><li>Example </li></ul><ul><ul><li>content://com.example.project:200/folder/subfolder/etc </li></ul></ul><ul><ul><li>The scheme is &quot;content&quot;, the host is &quot;com.example.project&quot;, the port is &quot;200&quot;, and the path is &quot;folder/subfolder/etc&quot;. </li></ul></ul><ul><ul><li>The host and port together constitute the URI authority </li></ul></ul><ul><li>When the URI in an Intent object is compared to a URI specification in a filter, it's compared only to the parts of the URI actually mentioned in the filter </li></ul><ul><ul><li>For example, if a filter specifies only a scheme, all URIs with that scheme match the filter. If a filter specifies a scheme and an authority but no path, all URIs with the same scheme and authority match, regardless of their paths. If a filter specifies a scheme, an authority, and a path, only URIs with the same scheme, authority, and path match. </li></ul></ul>
  98. 100. Data Test - Mime media type <ul><li>It's more common in filters than a URI. </li></ul><ul><li>Both the Intent object and the filter can use a &quot;*“ wildcard for the subtype field — for example, &quot;text/*&quot; or &quot;audio/*&quot; — indicating any subtype matches. </li></ul>
  99. 101. Data Test - Testing Rules <ul><li>An Intent object that contains neither a URI nor a data type passes the test only if the filter likewise does not specify any URIs or data types. </li></ul><ul><li>An Intent object that contains a URI but no data type passes the test only if its URI matches a URI in the filter and the filter likewise does not specify a type. </li></ul><ul><ul><li>This will be the case only for URIs like mailto: and tel: that do not refer to actual data. </li></ul></ul><ul><li>An Intent object that contains a data type but not a URI passes the test only if the filter lists the same data type and similarly does not specify a URI. </li></ul><ul><li>An Intent object that contains both a URI and a data type passes the data type part of the test only if its type matches a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a content: or file: URI and the filter does not specify a URI </li></ul>
  100. 102. Intent Resolution – Special Use Cases
  101. 103. .MAIN Action & .LAUNCHER Category <ul><li>Activities that can initiate applications have filters with &quot; android.intent.action.MAIN&quot; specified as the action </li></ul><ul><ul><li>This is a way an application gets started fresh, without a reference to any particular data. </li></ul></ul><ul><li>If they are to be represented in the application launcher, they also specify the &quot; android.intent.category.LAUNCHER&quot; category: </li></ul><ul><li><intent-filter . . . > </li></ul><ul><li><action android:name=&quot;code android.intent.action.MAIN&quot; /> </li></ul><ul><li><category android:name=&quot;code android.intent.category.LAUNCHER&quot; /> </li></ul><ul><li></intent-filter> </li></ul>
  102. 104. .MAIN Action & .LAUNCHER Category <ul><li>The Android system populates the application launcher, the top-level screen that shows the applications that are available for the user to launch, by finding all the activities with intent filters that specify the &quot;android.intent.action.MAIN&quot; action and &quot;android.intent.category.LAUNCHER“ category. It then displays the icons and labels of those activities in the launcher. </li></ul><ul><li>The Android system discovers the home screen by looking for the activity with &quot;android.intent.category.HOME&quot; in its filter </li></ul>
  103. 105. User Interface In Android
  104. 106. View and ViewGroup <ul><li>The user interface is built using View and ViewGroup objects. </li></ul><ul><li>During compilation time, each element in the XML file is compiled into its equivalent Android GUI class, with attributes represented by methods </li></ul><ul><li>A View : </li></ul><ul><ul><li>represents the basic building block for user interface components. </li></ul></ul><ul><ul><li>occupies a rectangular area on the screen and is responsible for drawing and event handling. </li></ul></ul><ul><ul><li>is the base class for widgets , which are used to create interactive UI components (buttons, text fields, etc.). </li></ul></ul><ul><ul><li>is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. </li></ul></ul><ul><ul><li>handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides </li></ul></ul><ul><ul><li>derives from the base class android.view.View. </li></ul></ul>
  105. 107. View and ViewGroup <ul><li>One or more Views can be grouped together into a ViewGroup. </li></ul><ul><li>The ViewGroup class serves as the base for subclasses called &quot;layouts,&quot; which offer different kinds of layout architecture, like linear, tabular and relative. </li></ul><ul><li>A ViewGroup derives from the base class. </li></ul><ul><li>android.view.ViewGroup </li></ul>
  106. 108. View Hierarchy <ul><li>All the views in a window are arranged in a tree you show the tree by calling setContentView(rootNode) in the activity </li></ul>
  107. 109. What is a Layout? <ul><li>Your layout is the architecture for the user interface in an Activity. </li></ul><ul><li>It defines the layout structure and holds all the elements that appear to the user. </li></ul>
  108. 110. How to declare a Layout? Two Options <ul><li>Option #1: Declare UI elements in XML (most common and preferred) </li></ul><ul><ul><li>Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for UI controls called widgets (TextView, Button, etc.) and layouts. </li></ul></ul><ul><li>Option #2: Instantiate layout elements at runtime (in Java code) </li></ul><ul><ul><li>Your application can create View and ViewGroup objects (and manipulate their properties) programmatically (in Java code). </li></ul></ul>
  109. 111. Example of using both options <ul><li>You can use either or both of these options for declaring and managing your application's UI </li></ul><ul><li>Example usage scenario </li></ul><ul><ul><li>You could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. </li></ul></ul><ul><ul><li>You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time. </li></ul></ul>
  110. 112. Advantages of Option #1: Declaring UI in XML <ul><li>Separation of the presentation from the code that controls its behavior </li></ul><ul><ul><li>You can modify UI without having to modify your source code and recompile </li></ul></ul><ul><ul><li>For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages </li></ul></ul><ul><li>Easier to visualize the structure of your UI (without writing any code) </li></ul><ul><ul><li>Easier to design/debug UI </li></ul></ul><ul><ul><li>Visualizer tool (like the one in Eclipse IDE) </li></ul></ul>
  111. 113. Layout File Structure <ul><li>Each layout file must contain exactly one root element, which must be a View (Button, for example) or ViewGroup object (LinearLayout, for example). </li></ul><ul><li>Once you've defined the root element, you can add additional layout objects or widgets (View) as child elements to gradually build a View hierarchy that defines your layout. </li></ul>
  112. 114. Example: Layout File <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> </li></ul><ul><li><LinearLayout </li></ul><ul><li>xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; </li></ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul><ul><li>android:layout_height=&quot;fill_parent&quot; </li></ul><ul><li>android:orientation=&quot;vertical&quot; > </li></ul><ul><li><TextView android:id=&quot;@+id/text&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:text=&quot;Hello, I am a TextView&quot; /> </li></ul><ul><li><Button android:id=&quot;@+id/button&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:text=&quot;Hello, I am a Button&quot; /> </li></ul><ul><li></LinearLayout> </li></ul>
  113. 115. Where to create Layout file? <ul><li>Save the file with the .xml extension, in your Android project's res/layout/ directory </li></ul>
  114. 116. Load the Layout XML Resource <ul><li>When you compile your application, each XML layout file is compiled into a View resource. </li></ul><ul><li>You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. </li></ul><ul><ul><li>By calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name </li></ul></ul><ul><li>public void onCreate(Bundle savedInstanceState) { </li></ul><ul><li>super.onCreate(savedInstanceState); </li></ul><ul><li>setContentView(R.layout.main_layout); </li></ul><ul><li>} </li></ul>
  115. 117. Attributes <ul><li>Every View and ViewGroup object supports their own variety of attributes. </li></ul><ul><ul><li>Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. </li></ul></ul><ul><ul><li>Some are common to all View objects, because they are inherited from the root View class (like the id attribute). </li></ul></ul><ul><ul><li>Other attributes are considered &quot;layout parameters,“ which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object. </li></ul></ul><ul><ul><li>These attributes are typically in XML form </li></ul></ul>
  116. 118. ID Attribute <ul><li>Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. </li></ul><ul><li>When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. </li></ul><ul><li>Syntax </li></ul><ul><ul><li>android:id=&quot;@+id/my_button&quot; </li></ul></ul>
  117. 119. ID Attribute - Android Resource ID <ul><li>There are a number of other ID resources that are offered by the Android framework. </li></ul><ul><li>When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace </li></ul><ul><ul><li>android:id=&quot;@android:id/empty“ </li></ul></ul><ul><li>With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class. </li></ul>
  118. 120. How to reference views in Java code? <ul><li>Assuming a view/widget is defined in the layout file with a unique ID </li></ul><ul><ul><li><Button android:id=&quot;@+id/my_button&quot; </li></ul></ul><ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>android:text=&quot;@string/my_button_text&quot;/> </li></ul></ul><ul><li>Then you can make a reference to the view object via findViewById(R.id.<string-id>). </li></ul><ul><ul><li>Button myButton = (Button) findViewById(R.id.my_button); </li></ul></ul>
  119. 121. What Are Layout Parameters? <ul><li>XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides </li></ul><ul><li>Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. </li></ul><ul><ul><li>This subclass contains property types that define the size and position for each child view, as appropriate for the view group. </li></ul></ul>
  120. 122. <ul><li>Parent view group defines layout parameters for each child view (including the child view group) </li></ul>
  121. 123. layout_width & layout_height <ul><li>wrap_content </li></ul><ul><ul><li>tells your view to size itself to the dimensions required by its content </li></ul></ul><ul><li>fill_parent </li></ul><ul><ul><li>tells your view to become as big as its parent view group will allow. </li></ul></ul><ul><li>match_parent </li></ul><ul><ul><li>Same as fill_parent </li></ul></ul><ul><ul><li>Introduced in API Level 8 </li></ul></ul><ul><ul><li><Button android:id=&quot;@+id/my_button&quot; </li></ul></ul><ul><ul><li>android:layout_width=&quot;match_parent&quot; </li></ul></ul><ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>android:text=&quot;@string/my_button_text&quot;/> </li></ul></ul>
  122. 124. Linear Layout fill_parent fill_parent Some Button... fill_parent wrap_content
  123. 125. Layout Types <ul><li>All layout types are subclass of ViewGroup class </li></ul><ul><li>Layout types </li></ul><ul><ul><li>LinearLayout </li></ul></ul><ul><ul><li>RelativeLayout </li></ul></ul><ul><ul><li>TableLayout </li></ul></ul><ul><ul><li>FrameLayout </li></ul></ul><ul><ul><li>Tab layout </li></ul></ul>
  124. 126. LinearLayout <ul><li>Aligns all children in a single direction — vertically or horizontally, depending on how you define the orientation attribute. </li></ul><ul><li>All children are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are </li></ul><ul><li>To configure a LinearLayout, you have five main areas of control besides the container's contents: </li></ul><ul><ul><li>Orientation </li></ul></ul><ul><ul><li>fill model </li></ul></ul><ul><ul><li>weight </li></ul></ul><ul><ul><li>gravity </li></ul></ul><ul><ul><li>padding </li></ul></ul>
  125. 127. LinearLayout <ul><li>Orientation : indicates whether the LinearLayout represents a row or a column. </li></ul><ul><li>Add the android:orientation property to your LinearLayout element in your XML layout, setting the value to be horizontal for a row or vertical for a column. </li></ul><ul><li>The orientation can be modified at runtime by invoking setOrientation() </li></ul>
  126. 128. LinearLayout
  127. 129. LinearLayout <ul><li>Linear Layout: Fill Model </li></ul><ul><li>Widgets have a &quot;natural&quot; size based on their accompanying text. </li></ul><ul><li>When their combined sizes does not exactly match the width of the Android device's screen, we may have the issue of what to do with the remaining space </li></ul>
  128. 130. LinearLayout <ul><li>Linear Layout: Fill Model </li></ul><ul><li>All widgets inside a LinearLayout must supply dimensional attributes android:layout_width and android:layout_height to help address the issue of empty space. </li></ul><ul><li>Values used in defining height and width are: </li></ul><ul><ul><li>Specific a particular dimension, such as 125px to indicate the widget should take up exactly 125 pixels. </li></ul></ul><ul><ul><li>Provide wrap content which means the widget should fill up its natural space, unless that is too big, in which case Android can use word‐wrap as needed to make it fit. </li></ul></ul><ul><ul><li>Provide fill_parent, which means the widget should fill up all available space in its enclosing container, after all other widgets are taken care of. </li></ul></ul>
  129. 131. LinearLayout <ul><li>Linear Layout: Fill Model </li></ul>
  130. 132. LinearLayout <ul><li>Linear Layout: Weight </li></ul><ul><li>It is used to proportionally assign space to widgets in a view. </li></ul><ul><li>You set android:layout_weight to a value (1, 2, 3, …) to indicates what proportion of the free space should go to that widget. </li></ul><ul><li>Example </li></ul><ul><ul><li>Both the TextView and the Button widgets have been set as in the previous example. Both have the additional property android:layout_weight=&quot;1“ whereas the EditText control has android:layout_weight=&quot;2“ </li></ul></ul>
  131. 133. LinearLayout <ul><li>Linear Layout: Gravity </li></ul><ul><li>It is used to indicate how a control will align on the screen. </li></ul><ul><li>By default, widgets are left‐ and top‐aligned. </li></ul><ul><li>You may use the XML property </li></ul><ul><li>android:layout_gravity=“…” </li></ul><ul><ul><li>to set other possible arrangements: left, center, right, top, bottom, etc. </li></ul></ul>
  132. 134. LinearLayout <ul><li>Linear Layout: Padding </li></ul><ul><li>By default, widgets are tightly packed next to each other. </li></ul><ul><li>If you want to increase the whitespace between widgets, you will want to use the android:padding property (or by calling setPadding() at runtime on the widget's Java object). </li></ul><ul><li>The padding specifies how much space there is between the boundaries of the widget's &quot;cell&quot; and the actual widget contents. </li></ul><ul><ul><li>Note: Padding is analogous to the margins on a word processing document. </li></ul></ul>
  133. 135. LinearLayout <ul><li>Linear Layout: Padding </li></ul><ul><li>Example: The EditText box has been changed to display 30px of padding all around </li></ul>
  134. 136. LinearLayout LinearLayout vertical LinearLayout horizontal weight=0.5 weight=0.5
  135. 137. RelativeLayout <ul><li>RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID) </li></ul><ul><ul><li>You can align two elements by right border, or make one below another, centered in the screen, centered left, and so on </li></ul></ul><ul><li>Elements are rendered in the order given, so if the first element is centered in the screen, other elements aligning themselves to that element will be aligned relative to screen center. </li></ul>
  136. 138. RelativeLayout toRightOf 1 1 parentTop parentLeft layout_below button1 2 parentBottom toRightOf 1
  137. 139. RelativeLayout : LayoutParams @+id/green @+id/red android:layout_above=&quot;@id/green&quot; android:layout_below=&quot;@id/red&quot; @+id/green @+id/red android:layout_toLeftOf=&quot;@id/green&quot; android:layout_toRightOf=&quot;@id/red&quot;
  138. 140. RelativeLayout : LayoutParams @+id/red @+id/red @+id/green android:layout_alignBottom=&quot;@id/red&quot; @+id/green android:layout_alignTop=&quot;@id/red&quot; @+id/green android:layout_alignLeft=&quot;@id/red&quot; @+id/green android:layout_alignRight=&quot;@id/red&quot;
  139. 141. RelativeLayout : LayoutParams android:layout_alignParentTop=&quot;true&quot; android:layout_alignParentLeft=&quot;true&quot; android:layout_alignParentBottom=&quot;true&quot; android:layout_alignParentRight=&quot;true&quot; parent @+id/red @+id/red
  140. 142. RelativeLayout Example <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> </li></ul><ul><li><RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android </li></ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:background=&quot;@drawable/blue&quot; </li></ul><ul><li>android:padding=&quot;10px&quot; > </li></ul><ul><li><TextView android:id=&quot;@+id/label&quot; </li></ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:text=&quot;Type here:&quot; /> </li></ul><ul><li><EditText android:id=&quot;@+id/entry&quot; </li></ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:background=&quot;@android:drawable/editbox_background&quot; </li></ul><ul><li>android:layout_below=&quot;@id/label&quot; /> </li></ul><ul><li><Button android:id=&quot;@+id/ok&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_below=&quot;@id/entry&quot; </li></ul><ul><li>android:layout_alignParentRight=&quot;true&quot; </li></ul><ul><li>android:layout_marginLeft=&quot;10px&quot; </li></ul><ul><li>android:text=&quot;OK&quot; /> </li></ul><ul><li><Button android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_toLeftOf=&quot;@id/ok&quot; </li></ul><ul><li>android:layout_alignTop=&quot;@id/ok&quot; </li></ul><ul><li>android:text=&quot;Cancel&quot; /> </li></ul><ul><li></RelativeLayout> </li></ul>
  141. 143. Table Layout <ul><li>Android's TableLayout allows you to position your widgets in a grid made of identifiable rows and columns. </li></ul><ul><li>Columns might shrink or stretch to accommodate their contents. </li></ul><ul><li>TableLayout works in conjunction with TableRow. </li></ul><ul><li>TableLayout containers do not display border lines for their rows, columns, or cells. </li></ul>
  142. 144. Table Layout <ul><li>Rows are declared by you by putting widgets as children of a TableRow inside the overall TableLayout. </li></ul><ul><li>The number of columns is determined by Android ( you control the number of columns in an indirect way). </li></ul><ul><li>So if you have three rows one with two widgets one with three rows, widgets, widgets, and one with four widgets, there will be at least four columns. </li></ul>
  143. 145. Table Layout <ul><li>However, a single widget can take up more than one column by including the android:layout_span property, indicating the number of columns the widget spans (this is similar to the colspan attribute one finds in table cells in HTML) </li></ul><ul><li><TableRow> </li></ul><ul><li><TextView android:text=&quot;URL:&quot; /> </li></ul><ul><li><EditText </li></ul><ul><li>android:id=&quot;@+id/entry&quot; </li></ul><ul><li>android:layout_span=&quot;3&quot; /> </li></ul><ul><li></TableRow> </li></ul>
  144. 146. Table Layout <ul><li>Ordinarily, widgets are put into the first available column of each row. </li></ul><ul><li>In the previous fragment, the label (“URL”) would go in the first column (column 0, as columns are counted starting from 0), and the TextField would go into a spanned set of three columns (columns 1 through 3). </li></ul>
  145. 147. Table Layout Example
  146. 148. Table Layout <ul><li>By default, each column will be sized according to the &quot;natural&quot; size of the widest widget in that column. </li></ul><ul><li>If your content is narrower than the available space, you can use the TableLayout property: </li></ul><ul><ul><li>android:stretchColumns =“ ” </li></ul></ul><ul><li>Its value should be a single column number (0‐based) or a comma delimited list of column numbers. Those columns will be stretched to take up any available space yet on the row. </li></ul>
  147. 149. Table Layout <ul><li>In our running example we stretch columns 2, 3, and 4 to fill the rest of the row. </li></ul>
  148. 150. Frame Layout <ul><li>FrameLayout is designed to block out an area on the screen to display a single item. </li></ul><ul><li>You can add multiple children to a FrameLayout and control their position within the FrameLayout using gravity. </li></ul><ul><li>Children are drawn in a stack, with the most recently added child on top. </li></ul><ul><li>The size of the frame layout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits). </li></ul>
  149. 151. Frame Layout Example <ul><li><FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; </li></ul><ul><li>android:layout_width=&quot;match_parent&quot; </li></ul><ul><li>android:layout_height=&quot;match_parent&quot;> </li></ul><ul><li><TextView </li></ul><ul><li>android:text=&quot;yellowyellowyellow&quot; </li></ul><ul><li>android:gravity=&quot;bottom&quot; </li></ul><ul><li>android:background=&quot;#aaaa00&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;120dip&quot;/> </li></ul><ul><li><TextView </li></ul><ul><li>android:text=&quot;greengreengreen&quot; </li></ul><ul><li>android:gravity=&quot;bottom&quot; </li></ul><ul><li>android:background=&quot;#00aa00&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;90dip&quot; /> </li></ul><ul><li><TextView </li></ul><ul><li>android:text=&quot;blueblueblue&quot; </li></ul><ul><li>android:gravity=&quot;bottom&quot; </li></ul><ul><li>android:background=&quot;#0000aa&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;60dip&quot; /> </li></ul><ul><li><TextView </li></ul><ul><li>android:text=&quot;redredred&quot; </li></ul><ul><li>android:gravity=&quot;bottom&quot; </li></ul><ul><li>android:background=&quot;#aa0000&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content&quot; </li></ul><ul><li>android:layout_height=&quot;30dip&quot;/> </li></ul><ul><li></FrameLayout> </li></ul>
  150. 152. ScrollView Layout <ul><li>A ScrollView is a special type of FrameLayout in that it enables users to scroll through a list of views that occupy more space than the physical display </li></ul><ul><li>When we have more data than what can be shown on a single screen you may use the ScrollView control. </li></ul><ul><li>It provides a sliding or scrolling access to the data. This way the user can only see part of your layout at one time, but the rest is available via scrolling. </li></ul><ul><li>The ScrollView can contain only one child view or ViewGroup, which normally is a LinearLayout. </li></ul><ul><li>This is similar to browsing a large web page that forces the user to scroll up the page to see the bottom part of the form. </li></ul>
  151. 153. Example of ScrollView
  152. 154. Absolute Layout <ul><li>Is based on the simple idea of placing each control at an absolute position.  </li></ul><ul><li>You specify the exact x and y coordinates on the screen for each control. </li></ul><ul><li>This is not recommended for most UI development since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain </li></ul><ul><li>This class is deprecated. </li></ul><ul><li>Use FrameLayout, RelativeLayout or a custom layout instead. </li></ul>
  153. 155. Adapting to Display Orientation <ul><li>One of the key features of modern smartphones is their ability to switch screen orientation. </li></ul><ul><li>Android supports two screen orientations </li></ul><ul><ul><li>portrait </li></ul></ul><ul><ul><li>Landscape </li></ul></ul><ul><li>When you change the orientation of your Android device, your current activity is actually destroyed and then re-created. </li></ul><ul><li>You can employ two techniques to handle changes in screen orientation </li></ul><ul><ul><li>Anchoring </li></ul></ul><ul><ul><li>Resizing and repositioning </li></ul></ul>
  154. 156. Adapting to Display Orientation
  155. 157. Adapting to Display Orientation <ul><li>Anchoring: </li></ul><ul><ul><li>The easiest way is to “anchor” your views to the four edges of the screen. </li></ul></ul><ul><ul><li>When the screen orientation changes, the views can anchor neatly to the edges. </li></ul></ul><ul><ul><li>Anchoring could be easily achieved by using RelativeLayout </li></ul></ul>
  156. 158. Adapting to Display Orientation ANCHORING VIEWS LANDSCAPE PORTRAIT
  157. 159. Adapting to Display Orientation <ul><li>Resizing and Repositioning </li></ul><ul><ul><li>customize the UI based on screen orientation is to create a separate res/layout folder containing the XML files for the UI of each orientation. </li></ul></ul><ul><ul><li>To support landscape mode, you can create a new folder in the res folder and name it as layout-land (representing landscape). </li></ul></ul><ul><ul><li>The main.xml file contained within the layout folder defines the UI for the activity in portrait mode, whereas the main.xml file in the layout-land folder defines the UI in landscape mode </li></ul></ul>
  158. 160. Persisting State Information during Changes in Configuration <ul><li>When an activity is re-created, the current state of the activity may be lost. </li></ul><ul><li>When an activity is killed, it will fire one or more of the following two events: </li></ul><ul><ul><li>onPause() </li></ul></ul><ul><ul><li>onSaveInstanceState(). </li></ul></ul><ul><li>To preserve the state of an activity, you could always implement the onPause() event. </li></ul><ul><li>If you simply want to preserve the state of an activity so that it can be restored later when the activity is re-created (such as when the device changes orientation), a much simpler way would be to implement the onSaveInstanceState() method </li></ul>
  159. 161. Detecting Orientation Changes <ul><li>Use the WindowManager class to know the device’s current orientation during run time. </li></ul><ul><li>//---get the current display info--- </li></ul><ul><li>WindowManager wm = getWindowManager(); </li></ul><ul><li>Display d = wm.getDefaultDisplay(); </li></ul><ul><li>if (d.getWidth() > d.getHeight()) </li></ul><ul><li>{ </li></ul><ul><li>//---landscape mode--- </li></ul><ul><li>}else </li></ul><ul><li>{ </li></ul><ul><li>//---portrait mode--- </li></ul><ul><li>} </li></ul>
  160. 162. Controlling the Orientation of the Activity <ul><li>You can programmatically force a change in orientation using the setRequestOrientation() method of the Activity class. </li></ul><ul><ul><li>setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); </li></ul></ul><ul><ul><li>setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); </li></ul></ul><ul><ul><li>you can also use the android:screenOrientation attribute on the <activity> element in AndroidManifest.xml </li></ul></ul>
  161. 163. View Widgets (android.view.View) <ul><li>Android’s GUI toolkit include all the common UI widgets like text labels, buttons, input fields, etc. </li></ul><ul><li>Widgets can be created and attached to our activities using Java code, in Android development it is more common to do it using XML-based layout files </li></ul><ul><li>Let‟s have a look at the following: </li></ul><ul><ul><li>TextView </li></ul></ul><ul><ul><li>EditText </li></ul></ul><ul><ul><li>Button </li></ul></ul><ul><ul><li>RadioGroup / RadioButton </li></ul></ul>
  162. 164. View Widgets (android.view.View) <ul><li>Labels </li></ul><ul><ul><li>In Android the label is referred to as a TextView. </li></ul></ul><ul><ul><li>The TextView is defined in main.xml, and placed into the activity’s view via a setcontentView call. </li></ul></ul><ul><ul><li><TextView </li></ul></ul><ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul></ul><ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>android:text=&quot;@string/hello&quot; </li></ul></ul><ul><ul><li>/> </li></ul></ul>
  163. 165. View Widgets (android.view.View) <ul><li>Buttons: </li></ul><ul><ul><li>The Android Button class is actually a subclass of TextView, to define a button we can try adding the following code to our layout xml file: </li></ul></ul><ul><ul><li><Button </li></ul></ul><ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul></ul><ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>android:text=&quot;Button&quot; </li></ul></ul><ul><ul><li>/> </li></ul></ul><ul><ul><li>android:id is the unique identifier of the element </li></ul></ul><ul><ul><li>android:layout_width/layout_height are the size of the element. In the android:text attribute we set the text that its inside the Button. </li></ul></ul>
  164. 166. View Widgets (android.view.View) <ul><li>Button : </li></ul><ul><li>We can have more attributes to configure our Button. </li></ul><ul><ul><li>android:clickable -> we set if the button reacts to click events </li></ul></ul><ul><ul><li>android:soundEffectsEnabled -> We can set if this button have sounds effects when its clicked or touched. </li></ul></ul><ul><ul><li>Most of the widget's attributes are shared because they have inherited them from more complex elements (Views). </li></ul></ul>
  165. 167. View Widgets (android.view.View) <ul><li>ImageView and ImageButton : </li></ul><ul><ul><li>are the image based versions of TextView and button </li></ul></ul><ul><ul><li>To specify the image to be used, we use the android:src attribute in the XML element, which usually references a drawable resource in the project. </li></ul></ul><ul><ul><li><ImageView </li></ul></ul><ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul></ul><ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>android:src=&quot;@drawable/icon&quot; </li></ul></ul><ul><ul><li>/> </li></ul></ul><ul><ul><li>ImageButton works the same way as the regular button </li></ul></ul>
  166. 168. View Widgets (android.view.View) <ul><li>EditText : </li></ul><ul><ul><li>Fields are input areas where the user can type in text </li></ul></ul><ul><ul><li>To use Android fields, use the EditText widget in the layout XML file </li></ul></ul><ul><ul><li><EditText </li></ul></ul><ul><ul><li>android:layout_width=&quot;fill_parent&quot; </li></ul></ul><ul><ul><li>android:layout_height=&quot;wrap_content&quot; </li></ul></ul><ul><ul><li>/> </li></ul></ul><ul><ul><li>The EditText widget is also a subclass of the TextView, but it has many other attributes that can be specified to alter the behavior of the field </li></ul></ul>
  167. 169. View Widgets (android.view.View) <ul><li>Checkbox : </li></ul><ul><ul><li>To use Android checkboxes, use the CheckBox widget in the layout XML file. </li></ul></ul><ul><ul><li><CheckBox android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;This is a checkbox&quot; /> </li></ul></ul><ul><ul><li>In Java, we can use the methods isChecked(), setChecked(), toggle() to check or modify the state of our checkbox. </li></ul></ul><ul><ul><li>we can implement the CompoundButton.OnCheckedChangedListener interface with our activity, and use setOnCheckedChangeListener() to attach a callback function to handle the check/uncheck events. </li></ul></ul>
  168. 170. View Widgets (android.view.View) <ul><li>Radiobuttons : </li></ul><ul><ul><li>Android’s RadioButton widget inherits from the CompoundButton, which in turn inherits from TextView. </li></ul></ul><ul><ul><li>Multiple RadioButtons can be put inside a RadioGroup, which means that only one button of the group can be selected at a time. </li></ul></ul>
  169. 171. View Widgets (android.view.View) <ul><li><RadioGroup android:id=&quot;@+id/myRadioGroup&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content“ android:layout_height=&quot;wrap_content&quot; </li></ul><ul><li>android:orientation=&quot;vertical&quot;> </li></ul><ul><li><RadioButtonandroid:id=&quot;@+id/radioButton01“ </li></ul><ul><li>android:text=&quot;RadioButton01&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content” android:layout_height=&quot;wrap_content&quot;> </li></ul><ul><li></RadioButton> </li></ul><ul><li><RadioButtonandroid:id=&quot;@+id/radioButton02“ </li></ul><ul><li>android:text=&quot;RadioButton02&quot; </li></ul><ul><li>android:layout_width=&quot;wrap_content“ android:layout_height=&quot;wrap_content&quot;> </li></ul><ul><li></RadioButton> </li></ul><ul><li></RadioGroup> </li></ul>
  170. 172. Using android.widget.Button <ul><li>To capture button clicks, we set up an event listener using the setOnClickListener method. E.g., we might use an (anonymous) inner class to capture button clicks, as is defined below: </li></ul><ul><li>Button button01=(Button)findViewById(R.id.button01); </li></ul><ul><li>button01.setOnClickListener(new View.OnClickListener() { </li></ul><ul><li>public void onClick(View v) { </li></ul><ul><li>Log.d(&quot;PropertyApp&quot;, &quot;button01 has just been pressed&quot;); </li></ul><ul><li>} </li></ul><ul><li>}); </li></ul>
  171. 173. Using android.widget.RadioButton <ul><li>To get the ID of a currently-checked radio button we use the getCheckedRadioButtonID method. E.g.: </li></ul><ul><li>RadioGroup myRadioGroup; </li></ul><ul><li>myRadioGroup=(RadioGroup)findViewById(R.id.myRadioGroup); </li></ul><ul><li>int checkedID = myRadioGroup.getCheckedRadioButtonId(); </li></ul><ul><li>if (checkedID == -1) { </li></ul><ul><li>Log.d(TAG, &quot;No radio button was selected.&quot;); </li></ul><ul><li>} else if (checkedID == R.id.radioButton01) { </li></ul><ul><li>Log.d(TAG, &quot;'radioButton01' was selected.&quot;); </li></ul><ul><li>} else if (checkedID == R.id.radioButton02) { </li></ul><ul><li>Log.d(TAG, &quot;'radioButton02' was selected.&quot;); </li></ul><ul><li>} </li></ul>
  172. 174. Creating Menus <ul><li>Menus are an important part of an activity's user interface, which provide users a familiar way to perform actions. </li></ul><ul><li>There are three types of application menus: </li></ul><ul><ul><li>Options Menu : </li></ul></ul><ul><ul><ul><li>The primary collection of menu items for an activity, which appears when the user touches the MENU button. </li></ul></ul></ul><ul><ul><ul><li>When your application is running on Android 3.0 or later, you can provide quick access to select menu items by placing them directly in the Action Bar, as &quot;action items.&quot; </li></ul></ul></ul>
  173. 175. Creating Menus <ul><li>Types of application menus: </li></ul><ul><ul><li>Context Menu </li></ul></ul><ul><ul><ul><li>A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu. </li></ul></ul></ul><ul><ul><li>Submenu </li></ul></ul><ul><ul><ul><li>A floating list of menu items that appears when the user touches a menu item that contains a nested menu. </li></ul></ul></ul>
  174. 176. Creating Menus <ul><li>Create an application that supports options/sub/context menus </li></ul><option menu> <sub-menu> <context menu> Automatically fill “Hi!” in the EditText Plus menu will also open a sub-menu Display messages when a menu clicked
  175. 177. Menu Composition Plus Home Pre Next <option menu> Sub1 Sub2 Hi Hola Hello <sub-menu> <context menu from EditText> Long press in EditText
  176. 178. Creating a Menu Resource <ul><li>Instead of instantiating a Menu in your application code, you should define a menu and all its items in an XML menu resource. </li></ul><ul><li>  Inflate the menu resource (load it as a programmable object) in your application code. </li></ul><ul><li>To create a menu resource, create an XML file inside your project's res/menu/ directory and build the menu with the following elements: </li></ul><ul><ul><li><menu> , <item>, <group> </li></ul></ul>
  177. 179. Creating a Menu Resource <ul><li><menu> </li></ul><ul><ul><li>Defines a Menu, which is a container for menu items </li></ul></ul><ul><ul><li>A <menu> element must be the root node for the file and can hold one or more <item> and <group>elements </li></ul></ul><ul><li><item> </li></ul><ul><ul><li>Creates a MenuItem, which represents a single item in a menu. </li></ul></ul><ul><ul><li>This element may contain a nested <menu> element in order to create a submenu. </li></ul></ul><ul><li><group> </li></ul><ul><ul><li>An optional, invisible container for <item> elements. </li></ul></ul><ul><ul><li>It allows you to categorize menu items so they share properties such as active state and visibility </li></ul></ul>
  178. 180. Creating a Menu Resource <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> <menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;>     <item android:id=&quot;@+id/new_game&quot;           android:icon=&quot;@drawable/ic_new_game&quot;           android:title=&quot;@string/new_game&quot; />     <item android:id=&quot;@+id/help&quot;           android:icon=&quot;@drawable/ic_help&quot;           android:title=&quot;@string/help&quot; /> </menu> </li></ul><ul><li>android:id </li></ul><ul><ul><li>A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it. </li></ul></ul><ul><li>android:icon </li></ul><ul><ul><li>A reference to a drawable to use as the item's icon. </li></ul></ul><ul><li>android:title </li></ul><ul><ul><li>A reference to a string to use as the item's title. </li></ul></ul>
  179. 181. Inflating a Menu Resource <ul><li>From your application code, you can inflate a menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). </li></ul><ul><li>public boolean onCreateOptionsMenu(Menu menu) {     MenuInflater inflater = getMenuInflater();     inflater.inflate(R.menu.game_menu, menu);     return true; } </li></ul><ul><li>The getMenuInflater() method returns a MenuInflater for the activity. </li></ul><ul><li>With this object, you can call inflate(), which inflates a menu resource into a Menuobject </li></ul>
  180. 182. Inflating a option menu resource <ul><li>Inflating a menu resource (menu.xml) by adding onCreateOptionsMenu(Menu menu) in the main Activity. </li></ul><ul><li>Menu items in menu.xml will appear when the user touches the MENU button </li></ul>public boolean onCreateOptionsMenu (Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu. menu , menu); return true; }
  181. 183. Response to user action <ul><li>Response to menu click events by overriding onOptionsItemSelected(Menu menu) in the main Activity. </li></ul><ul><li>  You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item </li></ul>@Override public boolean onOptionsItemSelected (MenuItem item) { switch (item.getItemId()) { case R.id.menuItemPlus: Toast.makeText(this, &quot;Plus Button Clicked !&quot;, Toast.LENGTH_SHORT).show(); Log.i(TAG,&quot;menuItemPlus&quot;); return true; : : case R.id.menuItemNext: Toast.makeText(this, &quot;Next Button Clicked !&quot;, Toast.LENGTH_SHORT).show(); Log.i(TAG,&quot;menuItemNext&quot;); return true; } return false; }
  182. 184. Changing menu items at runtime <ul><li>Once the activity is created, the onCreateOptionsMenu() method is called only once. </li></ul><ul><li>The system keeps and re-uses the Menu you define in this method until your activity is destroyed. </li></ul><ul><li>  If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu()method </li></ul>
  183. 185. How to Create Context Menu? <ul><li>A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu. </li></ul><ul><li>When Context menu is opened for the first time, the Android system will call the Activity's onCreateContextMenu(Menu menu) callback method. </li></ul><ul><ul><li>You, as a context menu developer, override this method in your Activity class and populate the Menu object given to you with MenuItem's. </li></ul></ul><ul><li>You can populate the menu in two ways </li></ul><ul><ul><li>Scheme #1: by calling add() for each item you'd like in the menu. </li></ul></ul><ul><ul><li>Scheme #2: by inflating a menu resource that was defined in XML (preferred) </li></ul></ul>
  184. 186. Populating Menu with Menu Items: #1 <ul><li>// Override this method of Activity class in order to create menu items. </li></ul><ul><li>@Override </li></ul><ul><li>public void onCreateContextMenu( </li></ul><ul><li>ContextMenu menu, // Context menu that is being built </li></ul><ul><li>View view, // The view for which the context menu is being built </li></ul><ul><li>ContextMenuInfo menuInfo) { </li></ul><ul><li>super.onCreateContextMenu(menu, view, menuInfo); </li></ul><ul><li>menu.setHeaderTitle(&quot;Context menu&quot;); </li></ul><ul><li>menu.add(0, Menu.FIRST , Menu.NONE, &quot;menu #1&quot;); </li></ul><ul><li>menu.add(0, Menu.FIRST + 1, Menu.NONE, &quot;menu #2&quot;); </li></ul><ul><li>menu.add(0, Menu.FIRST + 2, Menu.NONE, &quot;menu #3&quot;); </li></ul><ul><li>menu.add(0, Menu.FIRST + 3, Menu.NONE, &quot;menu #4&quot;); </li></ul><ul><li>} </li></ul>
  185. 187. How to handle User's Menu Selection? <ul><li>When a menu item is selected by a user from the Context Menu, onContextItemSelected() callback method of your Activity gets called </li></ul><ul><ul><li>This callback passes you the MenuItem that has been selected. </li></ul></ul><ul><ul><li>You can identify the item by requesting the itemId, with getItemId(), which returns the integer that was assigned with the add(int groupId, int itemId, int order, CharSequence title) method. </li></ul></ul><ul><ul><li>Once you identify the menu item, you can take an appropriate action. </li></ul></ul>
  186. 188. Example: Handling Menu Selection <ul><li>/* Handles item selections */ </li></ul><ul><li>public boolean onContextItemSelected(MenuItem item) { </li></ul><ul><li>switch (item.getItemId()) { </li></ul><ul><li>case MENU_NEW_GAME: </li></ul><ul><li>newGame(); </li></ul><ul><li>return true; </li></ul><ul><li>case MENU_QUIT: </li></ul><ul><li>quit(); </li></ul><ul><li>return true; </li></ul><ul><li>} </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul>
  187. 189. Creating Submenus <ul><li>A submenu is a menu that the user can open by selecting an item in another menu. </li></ul><ul><li>You can add a submenu to any menu (except a submenu). </li></ul><ul><li>Submenus are useful when your application has a lot of functions that can be organized into topics, like items in a PC application's menu bar (File, Edit, View, etc.). </li></ul>
  188. 190. Creating Submenus <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> <menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;>     <item android:id=&quot;@+id/file&quot;           android:icon=&quot;@drawable/file&quot;           android:title=&quot;@string/file&quot; >         <!-- &quot;file&quot; submenu -->         <menu>             <item android:id=&quot;@+id/create_new&quot;                   android:title=&quot;@string/create_new&quot; />             <item android:id=&quot;@+id/open&quot;                   android:title=&quot;@string/open&quot; />         </menu>     </item> </menu> </li></ul>
  189. 191. Creating Dialogs <ul><li>A dialog is usually a small window that appears in front of the current Activity. </li></ul><ul><li>The underlying Activity loses focus and the dialog accepts all user interaction. </li></ul><ul><li>Dialogs are normally used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress </li></ul>
  190. 192. Creating Dialogs <ul><li>The Dialog class is the base class for creating dialogs. </li></ul><ul><li>Typically you are going to use subclasses of Dialog class instead of using it directly. </li></ul><ul><li>Example subclasses of Dialog class : </li></ul><ul><ul><li>AlertDialog. </li></ul></ul><ul><ul><li>ProgressDialog </li></ul></ul><ul><ul><li>DatePickerDialog. </li></ul></ul><ul><ul><li>TimePickerDialog </li></ul></ul>
  191. 193. Showing a Dialog <ul><li>A dialog is always created and displayed as a part of an Activity. </li></ul><ul><li>You should normally create dialogs from within your Activity's onCreateDialog(int) callback method. </li></ul><ul><li>When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the &quot;owner&quot; of each dialog </li></ul>
  192. 194. Showing a Dialog <ul><li>When you want to show a dialog, call showDialog(int) and pass it an integer that uniquely identifies the dialog that you want to display. </li></ul><ul><li>When a dialog is requested for the first time, Android calls onCreateDialog(int) from your Activity, which is where you should instantiate the Dialog. </li></ul><ul><li>  Define  onPrepareDialog(int, Dialog) method if you want to change any properties of the dialog each time it is opened </li></ul>
  193. 195. Example of Showing a Dialog <ul><li>static final int DIALOG_PAUSED_ID = 0; </li></ul><ul><li>static final int DIALOG_GAMEOVER_ID = 1; </li></ul><ul><li>protected Dialog onCreateDialog(int id) {     Dialog dialog;     switch(id) {     case DIALOG_PAUSED_ID:         // do the work to define the pause Dialog         break;     case DIALOG_GAMEOVER_ID:         // do the work to define the game over Dialog         break;     default:         dialog = null;     }     return dialog; } </li></ul><ul><li>When it's time to show one of the dialogs,call  showDialog(int) with the ID of a dialog: </li></ul><ul><li>showDialog(DIALOG_PAUSED_ID); </li></ul>
  194. 196. Creating an Alert Dialog <ul><li>An AlertDialog is an extension of the Dialog class. </li></ul><ul><li>It should be used for dialogs that use any of the following features: </li></ul><ul><ul><li>A title </li></ul></ul><ul><ul><li>A text message </li></ul></ul><ul><ul><li>One, two, or three buttons </li></ul></ul><ul><ul><li>A list of selectable items (with optional checkboxes or radio buttons) </li></ul></ul>
  195. 197. Creating an Alert Dialog <ul><li>To create an AlertDialog, use the AlertDialog.Builder subclass. </li></ul><ul><li>Get a Builder with AlertDialog.Builder(Context) and then use the class's public methods to define all of the AlertDialog properties. </li></ul><ul><li>After you're done with the Builder, retrieve the AlertDialog object with create(). </li></ul>
  196. 198. Creating an Alert Dialog
  197. 199. Creating an Alert Dialog – Adding Buttons <ul><li>AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(&quot;Are you sure you want to exit?&quot;)        .setCancelable(false)        .setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int id) {                 MyActivity.this.finish();            }        })        .setNegativeButton(&quot;No&quot;, new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int id) {                 dialog.cancel();            }        }); AlertDialog alert = builder.create(); </li></ul>
  198. 200. Creating an Alert Dialog – Adding List <ul><li>final CharSequence[] items = {&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(&quot;Pick a color&quot;); builder.setItems(items, new DialogInterface.OnClickListener() {     public void onClick(DialogInterface dialog, int item) {         Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();     } }); AlertDialog alert = builder.create(); </li></ul>
  199. 201. Creating an Alert Dialog – Adding checkboxes and radio buttons <ul><li>To create a list of multiple-choice items (checkboxes) or single-choice items (radio buttons) inside the dialog, use the setMultiChoiceItems() and setSingleChoiceItems() methods </li></ul><ul><li>final CharSequence[] items = {&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(&quot;Pick a color&quot;); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {     public void onClick(DialogInterface dialog, int item) {         Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();     } }); AlertDialog alert = builder.create(); </li></ul>
  200. 202. Creating a ProgressDialog <ul><li>A ProgressDialog is an extension of the AlertDialog class. </li></ul><ul><li>It displays a progress animation in the form of a spinning wheel, for a task with progress that's undefined, or a progress bar, for a task that has a defined progression. </li></ul><ul><li>Opening a progress dialog can be as simple as calling ProgressDialog.show(). </li></ul><ul><li>ProgressDialog dialog = ProgressDialog.show(MyActivity.this, &quot;&quot;,                         &quot;Loading. Please wait...&quot;, true); </li></ul>
  201. 203. Creating a ProgressDialog <ul><li>The default style of a progress dialog is the spinning wheel. </li></ul><ul><li>If you want to create a progress bar that shows the loading progress with granularity, some more code is required. </li></ul><ul><li>To show the progression with an animated progress bar: </li></ul><ul><ul><li>Initialize the ProgressDialog with the class constructor, ProgressDialog(Context). </li></ul></ul><ul><ul><li>Set the progress style to &quot;STYLE_HORIZONTAL&quot; with setProgressStyle(int) and set any other properties, such as the message. </li></ul></ul><ul><ul><li>When you're ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback. </li></ul></ul><ul><ul><li>You can increment the amount of progress displayed in the bar by calling either setProgress(int) with a value for the total percentage completed so far or incrementProgressBy(int) with an incremental value to add to the total percentage completed so far. </li></ul></ul>
  202. 204. Date/Time Selection Widgets <ul><li>Date </li></ul><ul><ul><li>Android also supports widgets (DatePicker, TimePicker) and dialogs (DatePickerDialog, TimePickerDialog) for helping users enter dates and times. </li></ul></ul><ul><ul><li>The DatePicker and DatePickerDialog allow you to set the starting date for the selection, in the form of a year, month, and day. </li></ul></ul><ul><ul><li>Value of month runs from 0 for January through 11 for December </li></ul></ul><ul><ul><li>Each widget provides a callback object (OnDateChangedListener or OnDateSetListener) where you are informed of a new date selected by the user. </li></ul></ul>
  203. 205. Date/Time Select