Android Basics Mobile Application Development Selected Topics CPIT
Android Basics Mobile Application Development Selected Topics – CPIT 490 09 -Sep-20
Overview n n n Review Android Activities Android Intents User Interface / Views User Notifications 2
Developing for Android n n n n Eclipse Android SDK Android Development Tools (ADT) Android Virtual Devices (AVD) & SDK Manager The Android Emulator Dalvik Debug Monitor Services (DDMS) The Android Debug Bridge (ADB) 3
Android Software Stack 4
Android Project Structure n n n n src/ - Java packages. Each package can have multiple. java files representing different classes. res/layout/ - XML files that specify the layout of each screen. n main. xml defines the layout of the application. Default view is Layout view. res/values/ - XML files used as references by other files. res/drawable-hdpi/ , res/drawable-mdpi/ , and res/drawable-ldpi/ - high, medium, and low dots-per-inch resolution pictures. res/color, res/menu, res/anim assets/ - additional non-media files. Assets used by application. Ex. HTML, database, etc Android. Manifest. xml specifies the project to the Android OS. Permissions and other features are specified here. Auto-generated files (do not modify): n gen/ contains auto-generated code. Class R. java generated by Android Asset Packaging Tool (aapt). ). If you delete R. java, it will auto-generated again. R. java is based on Android. Manifest. xml file. n default. properties contains project settings. 5
Android Application Components n n n n i) Activity: Activity is a visual screen for interaction of user with the application. Depends upon design, an application may consists of one or more activities n Fragments: "miniature" activities that could be grouped to form an activity ii) Views: The User interface of an Activities is build with widgets. iii) Service: Service do not have a visual interface, it runs in the back ground, like play back music and fetching data from the network. iv) Broadcast Receiver: Broadcast receiver receive broadcast announcements and response to them according to the situation. v) Content Provider: Content provider is a SQLite database, which supports the sharing and accessing of data among applications. vi) Intents: Asynchronous messages which allow the application to request functionality from other services or activities. vii) Others parts are Android widgets / Live Folders and Live Wallpapers. 6
Android Activity n n n http: //developer. android. com/reference/android/app/Activity An "activity" is an application component that provides a screen with which users can interact Activity is usually a single screen n Implemented as a single class extending Activity n Displays user interface controls (views) n Reacts on user input / events An application typically consists of several activities n Each screen is typically implemented by one activity n Each activity can then start another activity (new screen) n An activity may return a result to the previous activity "main" activity is presented to the user when launching the application for the first time. Each activity receives callbacks due to a change in its state during its lifecycle — whether the system is creating it, stopping it, resuming it, or destroying it. 7
Activity Lifecycle 8
Activity Lifecycle n n Foreground Lifetime is until on. Pause() Visible Lifetime is until on. Stop() Entire Lifetime is until on. Destroy() Create an activity by extending Activity base class 9
Activity Example n n n extends Activity base class UI from res/layout folder R. layout. main refers to main. xml Android. Manifest. xml must declare all activities in the application @string refers to strings. xml in res/values folder on. Create() is involved when the activity is loaded 10
Activity Callbacks public class Activity extends Application. Context { n protected void on. Create(Bundle saved. Instance. State); // Called when the activity is first created. Provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by on. Start(). n protected void on. Start(); // Called when the activity is becoming visible to the user. Followed by on. Resume() if the activity comes to the foreground, or on. Stop() if it becomes hidden. n protected void on. Restart(); // Called after your activity has been stopped, prior to it being started again. Always followed by on. Start() n 11
Activity Callbacks protected void on. Resume(); // Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by on. Pause(). n protected void on. Pause(); // Called when the system is about to start resuming a previous activity. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either on. Resume() or on. Stop(). n protected void on. Stop(); // Called when the activity is no longer visible to the user. Followed by either on. Restart() if this activity is coming back to interact with user, or on. Destroy() if this activity is going away. n protected void on. Destroy(); // The final call you receive before your activity is destroyed. This can happen either because the activity is finishing or someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the is. Finishing() method. n } n 12
Activity Life cycle n n n n Activity is destroyed when the back button is pressed. So, if you want to preserve the state, we need to store the information before the application is destroyed on. Pause() is called when the application is send to background or when the application is killed on. Create() is invoked when the activity is loaded for the first time on. Start() and on. Resume() are invoked when an activity is started, either from background or newly started Use the on. Create() method to create and instantiate the objects that you will be using in your application Use the on. Resume() method to start any services or code that needs to run while your activity is in the foreground. Use the on. Pause() method to stop any services or code that does not need to run when your activity is not in the foreground. Use the on. Destroy() method to free up resources before your activity is 13 destroyed.
Utilizing Activity Lifecycle Functions n n n n Simple exercise to see the activity lifecycle in action each overridden function is explicit and a Toast command is added to show on screen when the function is entered Run it on an Android device and try various cases: Changing the screen orientation destroys and recreates the activity from scratch. Pressing the Home button pauses the activity, but does not destroy it. Pressing the Application icon might start a new instance of the activity, even if the old one was not destroyed. Letting the screen sleep pauses the activity and the screen awakening resumes it. (This is similar to taking an incoming phone call. ) 14
Activity Lifecycle Samples n n n Turn Display n on. Create(null) -> on. Start -> on. Resume() -> [Turn Display] > on. Save. Instance. State() -> on. Pause() -> on. Stop() -> on. Destroy() -> on. Create() -> on. Start() -> on. Restore. Instance. State() -> on. Resume() Home n on. Create(null) -> on. Start -> on. Resume() -> [Home Button] > on. Save. Instance. State() -> on. Pause() -> on. Stop() -> [Start App] > on. Restart() -> on. Start() -> on. Resume() Phone Call Interrupt n on. Create(null) -> on. Start -> on. Resume() -> [Phone Call] > on. Save. Instance. State() -> on. Pause() -> on. Stop() -> [Hang Up or press Back] > on. Restart() -> on. Start() -> on. Resume() 15
Notes on Activity n n Starting Activity: n void start. Activity (Intent intent) n void start. Activity. For. Result (Intent intent, int request. Code) n void on. Activity. Result (int request. Code, int result. Code, Intent data) Shutting Down Activity: n void finish () n void finish. Activity (int request. Code) Saving Activity Status n void on. Save. Instance. State (Bundle out. State) n void on. Restore. Instance. State (Bundle saved. Instance. State) Activity A starts Activity B: n A's on. Pause() n B's on. Create() , on. Start() , and on. Resume() (Activity B now has user focus. ) 16 n A’s on. Stop() , if A is no longer visible
Starting Activity 17
Saving Activity’s State 18
Back Stack Tasks and Activities Multiple Tasks Multiple Activity Instances 19
Activity and Android. Manifest. xml n Any new activity must be defined in Android. Manifest. xml file 20
Android. Manifest. xml and main. xml n n n n n version. Code: used to indicate the version number of the application version. Number: Represented as <major>. <minor> version numbers. This is displayed to the user Minimum, target and maximum SDK versions are specified here Icon of the application is provided via @drawable, which refers to the res/drawable folder The name of the main activity is provided. Also, the package name is provided android. intent. action. MAIN means that the current activity is the first activity that will be loaded when the application runs Under intent-filter <action android: name="a. b. c. d" /> means this specific activity could be invoked using a. b. c. d as the name android: window. Soft. Input. Mode="state. Hidden" is used to disable soft keyboard from appearing automatically for Edit. Text main. xml n android: on. Click="on. Click" is used to say which method to call when the view is clicked. The one in the quotes indicate the name of the method. This method is to be implemented in the java program. 21
Notes on Activity Contd… n n n n Killing an activity does not remove the application from memory, even if the application has only one activity Context class is used to provide references to your application. Activity class is a subclass of Context class. To draw progress dialogs, you could use progress. Dialog class. Applying dialog themes to an activity (in Android. Manifest. xml) (BAAD Pg 41) n android: theme="@android: style/Theme. Dialog"> Hides a feature (in *. java file) – Hide the title based on a state (BAAD Pg 42) n import android. view. Window; n //---hides the title bar--n request. Window. Feature(Window. FEATURE_NO_TITLE); Dialog box (BAAD Pg 42) Creating multiple activities and linking them using Intent (BAAD Pg 54) Passing parameters through intents (BAAD Pg 63) 22
Intents n n n http: //developer. android. com/reference/android/content/Intent. html Intents are used as a message-passing mechanism within your application and between applications. Intents are used to call built-in applications like Map, Browser, etc. n Explicit start Activity/Service using its class name n Start Activity/Service for an action with specific data n Broadcast that an event has occurred Consists of n Component name (name of component/activity to handle the intent) n Action to be performed (MAIN / VIEW / EDIT / PICK / DELETE) n Data to act on (expressed as URI) or Bundle n Categories n Extras (primitives / Strings / Serializable) n Flags 23
Component Name Field Specifies the name of the component (name of the activity if the component is activity) that should handle the intent n Class name of the target component (for example "First. Activity") <activity android: name =". First. Activity" android: labe l="@string/app_name"> <intent-filter > <action android: name = "edu. odu. examples. Intent. Activity" /> <category android: name = "android. intent. category. LAUNCHER" /> </intent-filter > </activity > n Setting component name is optional n Explicit Intent: If it is set, the Intent object is delivered to an instance of the designated class. Intent intent = new Intent (this, First. Activity. class); n Implicit Intent: If it is not set, Android uses other information (i. e. , action field) in the Intent object to locate a suitable target - this is called "intent resolution" Intent intent = new Intent ("edu. odu. examples. Intent. Activity"); n 24
Launching Activity n Intent Invocation Launch new activity (without receiving a result) n Launch new activity and expect result n n request. Code is simply an integer value that identifies an activity you are calling. This is to used to identify the activity that returns n For example, you may be calling multiple activities at the same time, and some activities may not return immediately (for example, waiting for a reply from a server) n request. Code of -1 is like start. Activity(intent) When activity exits, on. Activity. Result() method is called with given request. Code (int > 0) on. Activity. Result(int request. Code, int result. Code, Intent result) 25
Intents and Intent Filters n Description of what intents an activity can handle n Activities publish their intent filters in a manifest file <intent-filter > <action android: name="android. intent. action. VIEW"/> <category android: name="android. intent. category. DEFAULT"/> <category android: name="android. intent. category. BROWSABLE"/> <data android: scheme="geo"/> </intent-filter> n Upon invocation of start. Activity(intent) the system looks at the intent filters of all installed applications n Candidate activity that owns the filter must pass matching tests for action, category, and data fields http: //developer. android. com/guide/topics/intents-filters. html n 26
. MAIN Action &. LAUNCHER Category n n n Activities that can initiate applications have filters with "android. intent. action. MAIN" specified as the action n This is a way an application gets started fresh, without a reference to any particular data. If they are to be represented in the application launcher, they also specify the "android. intent. category. LAUNCHER" category: <intent-filter. . . > <action android: name="code android. intent. action. MAIN" /> <category android: name="code android. intent. category. LAUNCHER" /> </intent-filter> The Android system populates the application launcher by finding all the activities with intent filters that specify the "android. intent. action. MAIN" action and "android. intent. category. LAUNCHER" category. It then displays the icons and labels of those activities in the launcher. 27
Action Field n n n In Android, intents usually come in pairs: action and data. The action describes what is to be performed, such as editing an item, viewing the content of an item, and so on. The data specifies what is affected, such as a person in the Contacts database. The data is specified as an Uri object. Intent Resolution: Android OS looks for the activities which could satisfy the given request. For ex. , when we specify Intent i = new Intent("android. intent. action. VIEW"); the appropriate activity should be used to view. A string naming the action to be performed The Intent class defines a number of predefined action constants, including n ACTION_CALL, ACTION_EDIT, ACTION_MAIN, ACTION_SYNC, ACTION_BATTERY_LOW, etc. You can also define your own action strings for activating the components in your application The action largely determines how the rest of the intent is structured - particularly the data and extras fields - much as a method name determines a set of arguments and a return value. 28
Intent Actions n Note that Actions’ "Constant" could be replaced with an equivalent String constant. e. g. , : ACTION_CALL = "android. intent. action. CALL" 29
Data Field n n n The URI of the data to be acted on and the MIME type of that data. Use Uri. parse to convert string to an uri object Different actions are paired with different kinds of data specifications. If the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing. If the action is ACTION_CALL, the data field would be a tel: URI with the number to call. 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. Examples of Action/Data Pairs n ACTION_VIEW content: //contacts/people/ -- Display a list of people to browse through. n ACTION_VIEW content: //contacts/people/1 – Display information about person whose id is "1". n ACTION_DIAL content: //contacts/people/1 – Display the phone dialer with the person filled in. n ACTION_VIEW tel: 123 -- Display the phone dialer with the given number filled in. n ACTION_DIAL tel: 123 -- Dial the phone dialer with the given number filled in. 30
Example of Actions n n n Starting Activity: void start. Activity (Intent intent) Intent i = new Intent (this, Other. Activity. class); start. Activity(i); void start. Activity. For. Result (Intent intent, int request. Code) n void on. Activity. Result (int request. Code, int result. Code, Intent data) Shutting Down Activity: void finish() Intent intent = new Intent (this, First. Activity. class); start. Activity (intent); 31
Notes on Activity and Intents n n n n use the put. Extra() method of an Intent object to add a name/value pair n Two parameters in put. Extra(): one of type string and one of type integer you can also create a Bundle object and then attach it using the put. Extras() method get. Intent() method is used to get Intent object When a fragment is being created, it goes through the following states: on. Attach(), on. Create(), on. Create. View(), on. Activity. Created() When the fragment becomes visible, it goes through these states: on. Start(), on. Resume() When the fragment goes into the background mode, it goes through these states: on. Pause(), on. Stop() When the fragment is destroyed (when the activity it is currently hosted in is destroyed), it goes through the following states: on. Pause(), on. Stop(), on. Destroy. View(), on. Destroy(), on. Detach() Like activities, you can restore an instance of a fragment using a Bundle object, in the following states: on. Create(), on. Create. View(), on. Activity. Created() 32
Notes on Activity and Intents n n n n n on. Attached() — Called when the fragment has been associated with the activity on. Create. View() — Called to create the view for the fragment on. Activity. Created() — Called when the activity’s on. Create() method has been returned on. Destroy. View() — Called when the fragment’s view is being removed on. Detach() — Called when the fragment is detached from the activity <category android: name="android. intent. category. DEFAULT" /> should be used if you want an activity to be invoked by others Intents can be specified with categories in Androd. Manifest. xml file. You could specify the category in the code using add. Category(). If no category is specified in the java code, the DEFAULT category is invoked. If the category specified in the java code is not matched, then a runtime exception is generated and the activity will not be started Creating multiple activities and linking them using Intent (BAAD Pg 54) Passing parameters through intents (BAAD Pg 63) 33
Notes on Activity and Intents n n Using intents to start a second activity n Remember to add new Activity(s) to Android. Manifest. xml ! n Intent intent = new Intent(Context package. Context, Class<? > class); n package. Context = the activity we’re coming from n Class: the Activity in our app we’re going to n Intent intent = new Intent(this, Another. Activity. class); n start. Activity(i); Requesting and starting another application’s activity n Intent intent = new Intent(<action>, <data>); n ACTION_VIEW, ACTION_EDIT, ACTION_DIAL n scheme: //host/data/segments n Intent intent = new Intent(Intent. ACTION_DIAL, Uri. parse(“tel: 1234567890”)); 34
Notes on Activity and Intents n Activity Results n start. Activity. For. Result(intent) allows us to “return” data to the calling Activity n on. Activity. Result(int request. Code, int result. Code, Intent data); n request. Code: unique integer to determine what Activity returned n result. Code: RESULT_OK, RESULT_CANCELED n data: Intent to receive additional data n set. Result(int result. Code, Intent data); n result. Code: RESULT_OK, RESULT_CANCELED n data: Intent to pass additional data n finish() pops from stack and sends control back to previous Activity 35
Notes on Activity and Intents n n n Bundle objects store key and value pairs via the put<type> methods and get<type> methods n Basic data types: boolean, byte, char, double, float, int, long, etc. n Non-primitives: String, Serializable, Arrays Can get size() and key. Set() intent. put. Extras(Bundle bundle); n Associate a bundle with an intent get. Intent(). get. Extras(); n Get bundle associated with an intent. put. Extra(String key, value); n intent. get. Extra(String key); 36
Fragments n n n Fragments are mini-activities Fragments contain views as like Activities Fragments are contained within an activity. Fragments could be dynamically added or removed from the activity n the Fragment. Manager class is used to add fragments to an activity. n the Fragment. Transaction class is used to perform fragment transactions in your activity (such as add, remove or replace) n the Window. Manager to determine whether the device is currently in portrait mode or landscape mode n android. R. id. content refers to the content view of the activity n commit() method is to make changes to effect Add frames at run-time (BAAD Pg 74) When an activity goes background, it is moved to back state automatically. For fragments, moving to back state has to be done using add. To. Back. Stack(). Call inbuilt applications using Intent (BAAD Pg 85) 37
Fragments n n Three subclasses of fragments: List. Fragment, Dialog. Fragment, and Preference. Fragment A list fragment is a fragment that contains a List. View, displaying a list of items from a data source such as an array or a Cursor In the on. Create() event, you use the set. List. Adapter() method to programmatically fill the List. View with the content of the array The Array. Adapter object manages the array of strings that will be displayed by the List. View 38
User Interfaces and Views n n n n n Views are loaded from res/layout/main. xml file in the on. Create() method handler in your Activity class, using the set. Content. View() method of the Activity class Sometimes, you need to code the views in the java code itself because you need to generate the views at runtime. Ex. Games http: //developer. android. com/guide/topics/ui/index. html Views and View Groups Views (Widgets) Layouts Events Menus Dialogs Styles and themes 39
Fundamental UI Design n Views n Visual interface element (controls or widgets) n A view derives from the base class android. view. View. Group n Contains multiple widgets. Layouts inherit the View. Group class. Ex Linear. Layout, Absolute. Layout (deprecated), Table. Layout, Frame. Layout, etc n A View. Group derives from the base class android. view. View. Group Activities n Screen being displayed to the user. n Assign a View or layout to an Activity 40
Layouts n n n n http: //developer. android. com/guide/topics/ui/declaring-layout. html Layout contains Views Frame. Layout n Each child view is in reference to the top left corner. Use if only one View in screen at a time. Linear. Layout n Views in line, either vertically or horizontally. Single column or single row. Elements appear in order they are specified in the file Relative. Layout n Define positions of each other child view relative to each other and screen boundaries Table. Layout n Rows and Columns Web View n Display web pages 41
Layout Examples Linear Layout Relative Layout Grid Layout Tab Layout dp or dip — Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen. Recommended for layout dimensions. sp — Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes. pt — Point. A point is defined to be 1/72 of an inch, based on the physical screen size. px — Pixel. Corresponds to actual pixels on the screen. Not recommended. 42
Android Specifications n n Nexus S has a 4 -inch screen (diagonally), with a screen width of 2. 04 inches. Its resolution is 480 (width) 800 (height) pixels. With 480 pixels spread across a width of 2. 04 inches, the result is a pixel density of about 235 dots per inch (dpi). The pixel density of a screen varies according to screen size and resolution. Android defines and recognizes four screen densities: n Low density (ldpi) — 120 dpi n Medium density (mdpi) — 160 dpi n High density (hdpi) — 240 dpi n Extra High density (xhdpi) — 320 dpi Nexus S is in hdpi as its dpi is close to 240 dpi. Actual pixels = dp * (dpi / 160), where dpi is either 120, 160, 240, or 320. 43
Defining Layout n n n Using the dp unit ensures that your views are always displayed in the right proportion regardless of the screen density Portrait mode: n res/layout/main. xml Landscape mode: n res/layout-land/main. xml The default orientation layout is horizontal Each Activity can have it's own layout 44
Handling Orientation Changes n n Anchoring n Anchor your views to the corners (edges of the screen) n Achieved using Relative. Layout using options like n android: layout_align. Parent. Top="true" n android: layout_align. Parent. Right="true" Resizing and repositioning n Resizing every view according to the orientation n Write two main. xml files. One in res/layout folder and the other in res/layout-land folder Changing orientation kills an activity and recreates it. Only views that are named with android: id will persist orientation changes When an activity is killed, on. Pause() and on. Save. Instance. State() methods are invoked n Unlike the on. Pause() method, the on. Save. Instance. State() method is not fired when an activity is being unloaded from the stack (such as when the user pressed the back button), because there is no need to restore its state later n Preserve the state of your activity, such as using a database, internal or external file storage, and so on 45
Handling Orientation Changes Easier way to save state: on. Save. Instance. State() method provides a Bundle object as an argument so that you can use it to save your activity’s state n Information can only be saved in Bundle object and thus complex data structures cannot be stored @Override public void on. Save. Instance. State(Bundle out. State) { //---save whatever you need to persist--out. State. put. String(“ID”, “ 1234567890”); super. on. Save. Instance. State(out. State); } @ Override public void on. Restore. Instance. State(Bundle saved. Instance. State) { super. on. Restore. Instance. State(saved. Instance. State); //---retrieve the information persisted earlier--String ID = saved. Instance. State. get. String(“ID”); } n 46
Handling Orientation Changes on. Retain. Non. Configuration. Instance() method is fired when an activity is about to be destroyed due to a configuration change (such as a change in screen orientation, keyboard availability, etc. ) @Override public Object on. Retain. Non. Configuration. Instance() { //---save whatever you want here; it takes in an Object type--return(“Some text to preserve”); } n To extract the saved data, you can extract it in the on. Create() method, using the get. Last. Non. Configuration. Instance() method: @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); Log. d(“State. Info”, “on. Create”); String str = (String) get. Last. Non. Configuration. Instance(); } n 47
Detecting Orientation Changes Use Window. Manager class //---get the current display info--Window. Manager wm = get. Window. Manager(); Display d = wm. get. Default. Display(); if (d. get. Width() > d. get. Height()) { //---landscape mode--Log. d(“Orientation”, “Landscape mode”); } else { //---portrait mode--Log. d(“Orientation”, “Portrait mode”); } n Also, you could add android: screen. Orientation=”landscape” to activity in Android. Manifest. xml n If you wish to keep your application displayed in certain orientation, specify the below in on. Create() //---change to landscape mode--set. Requested. Orientation(Activity. Info. SCREEN_ORIENTATION_LANDSCAPE); For Portrait: Activity. Info. SCREEN_ORIENTATION_PORTRAIT 48 n
Example of Layout n n fill_parent fills the entire width or height of the parent wrap_content make the width or height to the content 49
Common Attributes n Refresh your Java programming The layout_gravity attribute indicates the positions the views should gravitate towards, while the layout_weight attribute specifies the distribution of available space 50
Example of Linear Layout <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout android: layout_width="fill_parent" android: layout_height="fill_parent" xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: stretchcolumns="*" > <Button android: layout_width="100 px" android: layout_height="wrap_content" android: text="Button A" android: layout_weight="0. 1" /> <Button android: layout_width="100 px" android: layout_height="wrap_content" android: text="Button B" android: layout_gravity="right" android: layout_weight="0. 3" /> <Edit. Text android: layout_width="fill_parent" android: layout_height="wrap_content" android: text. Size="18 sp" android: layout_weight="0. 6" /> </Linear. Layout> 51
Example of Table Layout <? xml version="1. 0" encoding="utf-8"? > <Table. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: layout_height="fill_parent" android: layout_width="fill_parent" android: background="#646464"> <Table. Row> <Text. View android: text="E-mail: " android: width="120 px" /> <Edit. Text android: id="@+id/email" android: width="200 px" /> </Table. Row> <Table. Row> <Text. View android: text="Password: " /> <Edit. Text android: id="@+id/password" android: password="true" /> </Table. Row> <Text. View /> <Check. Box android: id="@+id/remember. Me" android: text="Remember Me" /> </Table. Row> <Button android: id="@+id/sign. In" android: text="Log In" android: layout_span="2" /> </Table. Row> </Table. Layout> 52
Example of Relative Layout <? xml version="1. 0" encoding="utf-8"? > <Relative. Layout android: id="@+id/RLayout" android: layout_width="fill_parent" android: layout_height="fill_parent" xmlns: android="http: //schemas. android. com/apk/res/android" > <Text. View android: id="@+id/lbl. Comments" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text="Comments" android: layout_align. Parent. Top="true" android: layout_align. Parent. Left="true" /> <Edit. Text android: id="@+id/txt. Comments" android: layout_width="fill_parent" android: layout_height="170 px" android: text. Size="18 sp" android: layout_align. Left="@+id/lbl. Comments" android: layout_below="@+id/lbl. Comments" android: layout_center. Horizontal="true" /> <Button android: id="@+id/btn. Save" android: layout_width="125 px" android: layout_height="wrap_content" android: text="Save" android: layout_below="@+id/txt. Comments" android: layout_align. Right="@+id/txt. Comments" /> <Button android: id="@+id/btn. Cancel" android: layout_width="124 px" android: layout_height="wrap_content" android: text="Cancel" android: layout_below="@+id/txt. Comments" android: layout_align. Left="@+id/txt. Comments" /> </Relative. Layout> 53
Example of Frame Layout The Frame. Layout is a placeholder on screen that you can use to display a single view <? xml version="1. 0" encoding="utf-8"? > <Relative. Layout android: id="@+id/RLayout" android: layout_width="fill_parent" android: layout_height="fill_parent" xmlns: android="http: //schemas. android. com/apk/res/android" > <Text. View android: id="@+id/lbl. Comments" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text="Hello, Android!" android: layout_align. Parent. Top="true" android: layout_align. Parent. Left="true" /> <Frame. Layout android: layout_width="wrap_content" android: layout_height="wrap_content" android: layout_align. Left="@+id/lbl. Comments" android: layout_below="@+id/lbl. Comments" android: layout_center. Horizontal="true" > <Image. View android: src = "@drawable/droid" android: layout_width="wrap_content" android: layout_height="wrap_content" /> </Frame. Layout> </Relative. Layout> 54
Scroll. View n n n A Scroll. View is a special type of Frame. Layout in that it enables users to scroll through a list of views that occupy more space than the physical display The Scroll. View can contain only one child view or View. Group, which normally is a Linear. Layout The List. View is designed for showing a list of related information and is optimized for dealing with large lists. So, don’t use List. View with Scroll. View <Scroll. View android: layout_width=”fill_parent” android: layout_height=”fill_parent” xmlns: android=”http: //schemas. android. com/apk/res/android” > <Linear. Layout android: layout_width=”fill_parent” android: layout_height=”wrap_content” android: orientation=”vertical” android: focusable=”true” android: focusable. In. Touch. Mode=”true”> <Button android: id=”@+id/button 1” android: layout_width=”fill_parent” android: layout_height=”wrap_content” android: text=”Button 1” /> <Button android: id=”@+id/button 2” android: layout_width=”fill_parent” android: layout_height=”wrap_content” android: text=”Button 2” /> <Button android: id=”@+id/button 3” android: layout_width=”fill_parent” android: layout_height=”wrap_content” android: text=”Button 3” /> <Edit. Text android: id=”@+id/txt” android: layout_width=”fill_parent” android: layout_height=” 600 dp” /> <Button android: id=”@+id/button 4” android: layout_width=”fill_parent” android: layout_height=”wrap_content” android: text=”Button 4” /> <Button android: id=”@+id/button 5” android: layout_width=”fill_parent” android: layout_height=”wrap_content” android: text=”Button 5” /> </Linear. Layout> </Scroll. View> 55
Defining Styles n n Multiple Buttons Define style only once! . . . <Table. Row android: id="@+id/Table. Row 01" android: layout_weight="0. 2" android: layout_width="fill_parent" android: layout_height="wrap_content"> <Button android: id="@+id/Button 07" style="@style/mybutton" android: text="7" /> <Button android: id="@+id/Button 08" style="@style/mybutton" android: text="8" /> <Button android: id="@+id/Button 09" style="@style/mybutton" android: text="9" /> <Button android: id="@+id/Button. Divide" style="@style/mybutton" android: text="/" /> </Table. Row> … 56
Styles in values/styles. xml <? xml version="1. 0" encoding="utf-8"? > <resources> <style name="mybutton" parent="@android: style/Text. Appearance"> <item name="android: text. Size">30 sp</item> <item name="android: text. Color">#000000</item> <item name="android: layout_width">fill_parent</item> <item name="android: layout_height">fill_parent</item> <item name="android: layout_weight">1</item> </style> </resources> 57
Styles and Themes n n n Way of building and formatting layout to your app Style has formatting attributes to several elements The format for the value of the style attribute is as follows: ? [package: ][type: ]name Theme has formatting attributes to all activities n Create theme in xml (styles. xml) n Apply theme in manifest To hide the action bar, add android: theme="@android: style/Theme. Holo. No. Action. Bar" to Android. Manifest. xml Hide action bar programmatically import android. app. Action. Bar; Action. Bar action. Bar = get. Action. Bar(); action. Bar. hide(); //action. Bar. show(); //---show it again--58
Action. Bar To add a home button at the Action. Bar and move to the main activity when it is clicked. case android. R. id. home: Toast. make. Text(this, “You clicked on the Application icon”, Toast. LENGTH_LONG). show(); Intent i = new Intent(this, My. Action. Bar. Activity. class); i. add. Flags(Intent. FLAG_ACTIVITY_CLEAR_TOP); start. Activity(i); return true; The Intent. FLAG_ACTIVITY_CLEAR_TOP flag ensures that the series of activities in the back stack is cleared when the user clicks the application icon on the Action Bar. This way, if the user clicks the back button, the other activities in the application do not appear again. n 59
Progress. Bar Add Progress. Bar in main. xml <Progress. Bar android: id=”@+id/progressbar” android: layout_width=”wrap_content” android: layout_height=”wrap_content” style=”@android: style/Widget. Progress. Bar. Horizontal” /> n To display the progress, call its set. Progress() method, passing in an integer indicating its progress n Various Progress. Bar styles: Widget. Progress. Bar. Horizontal, Widget. Progress. Bar. Small, Widget. Progress. Bar. Large, Widget. Progress. Bar. Inverse, Widget. Progress. Bar. Small. Inverse, Widget. Progress. Bar. Large. Inverse n 60
UI Programmatically n n n Comment set. Content. View(R. layout. main); in on. Create() Specify the layout parameters for the views using Layout. Params object n //---param for views--n Layout. Params params = new Linear. Layout. Params(Layout. Params. FILL_PARENT, Layout. Params. WRA P_CONTENT); The respective layout object should also be created n Linear. Layout layout = new Linear. Layout(this); n layout. set. Orientation(Linear. Layout. VERTICAL); Create Text. View and Button and add them to the layout object, using add. View() n Text. View tv = new Text. View(this); n Button btn = new Button(this); n layout. add. View(tv); layout. add. View(btn); Create the parameters to be used by the layout Add the layout to the activity: this. add. Content. View(layout, layout. Param); 61
Views (Input Controls/Widgets) n n n n Text. View n Label Edit. Text n Editable text Button n Standard push button Check. Box n Standard checkbox Radio. Button n Standard radio button List. View n View group that manages a group of Views. Spinner n Text. View associated with List. View. Let's you select an item from a list. 62
Other Views and Widgets n n n Widget and Other View http: //developer. android. com/resources/tutorials/views/index. html Package android. widget http: //developer. android. com/reference/android/widget/packa ge-summary. html view - API Demos (Sample Code) http: //developer. android. com/resources/samples/Api. Demos/sr c/com/example/android/apis/view/index. html 63
Event Listener (Input Events) n n n An interface, in the View class, that contains a single callback method Called by the Android framework when the View is triggered Multiple Event. Listeners (Interfaces): n View. On. Click. Listener - on. Click() n View. On. Long. Click. Listener - on. Long. Click() n View. On. Focus. Change. Listener - on. Focus. Change() n View. On. Key. Listener - on. Key() n View. On. Touch. Listener - on. Touch() n View. On. Create. Context. Menu. Listener - on. Create. Context. Menu() When a menu item is selected, on. Options. Item. Selected() method is called The Action Bar populates its action items by calling the on. Create. Options. Menu() method of an activity To set a menu in the action bar, use set. Show. As. Action(Menu. Item. SHOW_AS_ACTION_IF_ROOM) 64
Event Listener (Input Events) The on. Checked. Changed() method can be used with Radio. Button and Toggle. Button. Check. Box check. Box = (Check. Box) find. View. By. Id(R. id. chk. Autosave); check. Box. set. On. Click. Listener(new View. On. Click. Listener() { public void on. Click(View v) { if (((Check. Box)v). is. Checked()) Display. Toast("Check. Box is checked"); else Display. Toast("Check. Box is unchecked"); } }); //---Radio. Button--Radio. Group radio. Group = (Radio. Group) find. View. By. Id(R. id. rdb. Gp 1); radio. Group. set. On. Checked. Change. Listener(new On. Checked. Change. Listener() { public void on. Checked. Changed(Radio. Group group, int checked. Id) { Radio. Button rb 1 = (Radio. Button) find. View. By. Id(R. id. rdb 1); if (rb 1. is. Checked()) { Display. Toast("Option 1 checked!"); } else { Display. Toast("Option 2 checked!"); } } }); n 65
UI Notifications n n on. Key. Down — Called when a key was pressed and not handled by any of the views contained within the activity on. Key. Up — Called when a key was released and not handled by any of the views contained within the activity on. Menu. Item. Selected — Called when a panel’s menu item has been selected by the user on. Menu. Opened — Called when a panel’s menu is opened by the user 66
Example: on. Click() for Button view public class Example. Activity extends Activity implements On. Click. Listener { protected void on. Create (Bundle saved. Values) { . . . Button button = (Button) find. View. By. Id(R. id. button_1); button. set. On. Click. Listener(this); } // Implement the On. Click. Listener callback public void on. Click(View v) { switch (v. get. Id()) { case R. id. button_1: // do action when the button is clicked break; // handle more buttons in the activity } } . . . } 67
Views with images n n n Images could be brought into views using Image. View, Gallery, Image. Switcher, Grid. View The Gallery is a view that shows items (such as images) in a center-locked, horizontal scrolling list The Grid. View shows items in a two-dimensional scrolling grid. You can use the Grid. View together with an Image. View to display a series of images Image. Adapter class (which extends the Base. Adapter class) is used to bind the Gallery view with a series of Image. View views. The Base. Adapter class acts as a bridge between an Adapter. View and the data source that feeds data into it. Examples of Adapter. Views are: List. View, Grid. View, Spinner, Gallery Subclasses of the Base. Adapter class: List. Adapter, Array. Adapter, Cursor. Adapter, Spinner. Adapter 68
Menus n n n Options Menu n Compact menu bottom of the screen n Information on current activity Context Menu n Tap and hold on an element n Information about particular view Popup Menu n List of items based on the current view 69
Options Menus // The on. Create. Options. Menu() method is called when the MENU button is pressed. // When a menu item is selected, the on. Options. Item. Selected() method is called public class Menu. Example extends Activity { @Override public void on. Create(Bundle saved. Instance. State) {. . . } // Modify menu items dynamically. Disable/enable menu items. @Override public boolean on. Prepare. Options. Menu(Menu menu) {. . . } // Create your menu here @Override public boolean on. Create. Options. Menu(Menu menu) {. . . } // When menu item is selected @Override public boolean on. Options. Item. Selected(Menu. Item item) {. . . } } 70
Creating Menus in XML (res/menu. xml) Creating a Menu Resource <? xml version = "1. 0" encoding = "utf-8" ? > <menu xmlns: android = "http: //schemas. android. com/apk/res/android" > <item android: id = "@+id/new_game" android: icon = "@drawable/ic_new_game" android: title = "@string/new_game" /> <item android: id = "@+id/help" android: icon = "@drawable/ic_help" android: title = "@string/help" /> </menu> Inflating a Menu Resource @Override public boolean on. Create. Options. Menu(Menu menu) { super. on. Create. Options. Menu(menu) ; Menu. Inflater inflater = get. Menu. Inflater (); inflater. inflate(R. menu. game_menu, menu ); return true ; } 71
Responding to Menu Selection @Override public boolean on. Options. Item. Selected (Menu. Item item) { // Handle item selection switch(item. get. Item. Id()) { case R. id. new_game : new. Game(); return true ; case R. id. help : show. Help(); return true ; default: return super. on. Options. Item. Selected(item); } } 72
Changing Menu Dynamically @Override public boolean on. Prepare. Options. Menu(Menu menu){ super. on. Prepare. Options. Menu(menu); Menu. Item menu. Item 1 = menu. find. Item(R. id. new_game); menu. Item 1. set. Enabled(false); Menu. Item menu. Item 2 = menu. get. Item(0); menu. Item 2. set. Enabled(false); return true; } 73
Submenu A sub menu can be added within any menu <? xml version="1. 0" encoding="utf-8"? > <menu xmlns: android = "http: //schemas. android. com/apk/res/android" > <item android: id = "@+id/file" android: icon = "@drawable/file" android: title = "@string/file" > <!-- "file" submenu --> <menu> <item android: id = "@+id/create_new" android: title = "@string/create_new" /> <item android: id = "@+id/open" android: title = "@string/open" /> </menu> </item> </menu> n 74
Creating Menus in Java public class Menu. Example extends Activity { // You can increment this for additional menuitems static final private int MENU_ITEM 1 = Menu. FIRST; static final private int MENU_ITEM 2 = Menu. FIRST + 1; // Create your menu here @Override public boolean on. Create. Options. Menu(Menu menu) { super. on. Create. Options. Menu(menu); // Specify group value to separate Menu Items for batch processing and // ordering. NONE = No group int group. Id = Menu. NONE; // Unique identifier for each menu item (used for event handling) int menu. Item. Id 1 = MENU_ITEM 1; int menu. Item. Id 2 = MENU_ITEM 2; // Order value. Menu. NONE = I don't care int menu. Item. Order = Menu. NONE; // Menu Text int menu. Item. Text 1 = R. string. menu_item 1; int menu. Item. Text 2 = R. string. menu_item 2; menu. add(group. Id, menu. Item. Id 1, menu. Item. Order, menu. Item. Text 1); menu. add(group. Id, menu. Item. Id 2, menu. Item. Order, menu. Item. Text 2); // group. Id — The group identifier that the menu item should be part of. Use 0 if an item is not in a Group; item. Id — A unique item ID; order — The order in which the item should be displayed; title — The text to display for the menu item; set. Alphabetic. Shortcut() method can assign shortcut key to menu item return true; } } 75
Context Menu n n Context Menu = Long press set. On. Create. Context. Menu. Listener() is used to add context menu for an activity Override two methods on a Activity n on. Create. Context. Menu(): Called when a user taps and holds the button n on. Context. Item. Selected(): Called when an item inside the context menu is selected Register the context menu to the view n register. For. Context. Menu(view) For details on menu, and other resources: http: //developer. android. com/guide/topics/resources/availableresources. html 76
Example public class My. Context. Menu extends Activity { private Text. View tv; @Override public void on. Create(Bundle saved. Instance. State) { } @Override public void on. Create. Context. Menu(Context. Menu menu, View v, Context. Menu. Info menu. Info) { } @Override public boolean on. Context. Item. Selected(Menu. Item item) { } } 77
On. Create @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); tv = new Text. View(this); tv. set. Text("Context Menu!") ; register. For. Context. Menu(tv) ; //or //tv. set. On. Creat. Context. Menu. Listener(this); set. Content. View(tv); } 78
On. Create. Context. Menu @Override public void on. Create. Context. Menu(Context. Menu menu, View v, Context. Menu. Info menu. Info) { super. on. Create. Context. Menu(menu, v, menu. Info); if (v == tv) { Menu. Inflater inflater = get. Menu. Inflater(); inflater. inflate(R. menu. mymenu, menu); } } 79
On. Context. Item. Selected @Override public boolean on. Context. Item. Selected(Menu. Item item) { super. on. Context. Item. Selected(item) ; switch(item. get. Item. Id()){ case R. id. a: Toast. make. Text (this, "A", 1000). show(); return true; case R. id. b: Toast. make. Text (this, "B", 1000). show(); return true; } return false; } 80
Menus – Summary n n n n Described in XML, stored in res/menu <menu> has many <item> children Accessed like other resources (R. menu. <filename>) on. Create. Options. Menu(Menu menu) n User presses menu button on device on. Create. Context. Menu(Context. Menu menu, View v, Context. Menu. Info menu. Info) n User holds down a view (right-clicking/long press) n Need to register. For. Context. Menu(View v) on. Options. Item. Selected(Menu. Item item) n User selects an option from the menu coming from the menu button on. Context. Item. Selected(Menu. Item item) n User selected an option from a context menu Item. get. Item. Id() n Gets ID of selected item 81
Menus – Summary n n <item> elements can also contain other <menu> items! When <item> is selected, a submenu will open as a context menu 82
Other views For Clock view, in main. xml: <Analog. Clock android: layout_width=”wrap_content” android: layout_height=”wrap_content” /> <Digital. Clock android: layout_width=”wrap_content” android: layout_height=”wrap_content” /> n Web. View: Embed a web browser in your activity n Handle website redirects within the application itself without opening the Browser application using should. Override. Url. Loading() method n Dynamic loading of HTML is done using load. Url(file: ///) n 83
User Notification n Toast Notification n Brief message Status Bar Notification n Persistent reminder Dialog Notification n Activity-related notification 84
User Notification n Toast appears and disappears in few seconds. Thus, it is better to use Notifications A Pending. Intent object helps you to perform an action on your application’s behalf, often at a later time, regardless of whether your application is running or not. The get. Activity() method retrieves a Pending. Intent object and you set it using the following arguments: n context — Application context n request code — Request code for the intent n intent — The intent for launching the target activity n flags — The flags in which the activity is to be launched 85
Toast n Toast. make. Text(this, "Reset", 1000). show(); 86
Status Bar Notification n n Adds an icon to the system's status bar n Expanded message in the notification window n Optional ticker-text message n Highly configurable If your app is working in the background, give status bar notifications 87
The Basics n n n Usually a Service is launching the status bar notification You must use two classes: Notification and Notification. Manager Instance of Notification should have all the information about the notification (e. g. , icon, the expanded message) Notification. Manager is an Android system that executes and manages all the notifications You don't instantiate Notification. Manager 88
Get Reference to Notification. Manager n n String ref = Context. NOTIFICATION_SERVICE; Notification. Manager m. Notification. Manager = (Notification. Manager) get. System. Service(ref); 89
Instantiate the Notification notification = new Notification(R. drawable. notify_icon, "Hello", System. current. Time. Millis()); 90
Define the Notification’s expanded message and Intent Refresh your Java programming // Communication between status bar and this Activity Intent notification. Intent = new Intent(this, My. Context. Menu. class); Pending. Intent content. Intent = Pending. Intent. get. Activity(this, 0, notification. Intent, 0); notification. set. Latest. Event. Info(this, "My notification", "Hello World!", content. Intent); n 91
Pass the Notification to the Notification. Manager n m. Notification. Manager. notify(1, notification); 92
Status Bar Notification String ns = NOTIFICATION_SERVICE; Notification. Manager m. Notification. Manager = (Notification. Manager) get. System. Service(ns); int icon = R. drawable. icon; Char. Sequence ticker. Text = "Calculator Reseted!"; long when = System. current. Time. Millis(); Notification notification = new Notification(icon, ticker. Text, when); Intent notification. Intent = new Intent(this, My. Activity. class); Pending. Intent content. Intent = Pending. Intent. get. Activity(this, 0, notification. Intent, 0); notification. set. Latest. Event. Info(this, "My Calculator", "The calculator was reseted!", content. Intent); m. Notification. Manager. notify(1, notification); http: //developer. android. com/guide/topics/ui/notifiers/notifications. html 93
Dialogs n n Alert. Dialog Progress. Dialog Date. Picker. Dialog Time. Picker. Dialog 94
Example of Alert. Dialog. Builder builder = new Alert. Dialog. Builder(this); builder. set. Message("Hello!") . set. Positive. Button("Ok", new Dialog. Interface. On. Click. Listener() { public void on. Click(Dialog. Interface dialog, int id) { dialog. cancel(); } }) . set. Negative. Button("Cancel", new Dialog. Interface. On. Click. Listener() { public void on. Click(Dialog. Interface dialog, int id) { dialog. cancel(); } }); Alert. Dialog alert = builder. create(); alert. show(); http: //developer. android. com/guide/topics/ui/dialogs. html 95
Example of Progress. Dialog n n Progress. Dialog dialog = Progress. Dialog. show(this, "", "Loading. Please wait. . . "); dialog. show(); 96
Android Logging Options n n n The Log. e() method is used to log errors. The Log. w() method is used to log warnings. The Log. i() method is used to log informational messages. The Log. d() method is used to log debug messages. The Log. v() method is used to log verbose messages. The Log. wtf() method is used to log terrible failures that should never happen. ("WTF" stands for "What a Terrible Failure!" of course. ) n private static final String TAG = "My. App"; n Log. i(TAG, "I am logging something informational!"); 97
Debug n n (Window > Open Perspective > Debug) <application android: icon= "@drawable/icon" android: label="@string/app_name" android: debuggable="true" > 98
Tools n n Droid. Draw: n http: //www. droiddraw. org/ Video: n http: //marakana. com/forums/android/general/212. html 99
Recommended to try n n n p 38: Understanding the Life Cycle of an Activity p 42: Displaying a Dialogue Window using an Activity p 50: Displaying the progress of an operation p 54: Linking Activities with Intents p 130: Understanding Activity Behavior when Orientation Changes p 161: Using the Basic Views p 168: Handling View Events p 191: Displaying a Long List of Items using the List. View p 197: Checking which Items are Selected p 235 Creating the Menu Helper Methods p 238: Displaying an Option Menu p 240: Displaying a Context Menu 100
References n App Development for Smart Devices n http: //www. cs. odu. edu/~cs 495/ 101
- Slides: 101