HIT3328 - Chapter03 - Simple Interactive Apps
Upcoming SlideShare
Loading in...5
×
 

HIT3328 - Chapter03 - Simple Interactive Apps

on

  • 229 views

 

Statistics

Views

Total Views
229
Views on SlideShare
229
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    HIT3328 - Chapter03 - Simple Interactive Apps HIT3328 - Chapter03 - Simple Interactive Apps Document Transcript

    • HIT3328 / HIT8328 Software Development forMobile DevicesDr. Rajesh Vasa, 2012Twitter: @rvasaBlog: http://rvasa.blogspot.com1Lecture 03Simple InteractiveAppsR. Vasa, 2012Lecture Overview• Recap• UI Construction - Separation of Concerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources (Programatically)• Working with Alternate Layouts2R. Vasa, 20113When building mobile apps...• Assume phone will ring• Save state regularly (in fact, beparanoid)• Assume O/S allocates resources reluctantly• Assume erratic network connectivity• Assume slow read/write speed to Flash card• Use RAM carefully, minimise sensor use• Inform user if any operation takes over 3sec.• Keep core use case as short as possibleR. Vasa, 20124Android Device UserInteraction• Android has a three key buttonsMenuHomeBackR. Vasa, 20125Android PlatformImage Source: http://www.tbray.orgJavaC/C++R. Vasa, 20116The Android Way - Convention notConfig.• Source code (src)• Generated code (gen)• Resources (res)• Images (@drawable)• Layout of app (layout)• Constants/Strings (@strings)
    • R. Vasa, 20127Android App. is made ofActivitiesActivityView GroupViews(Layout)R. Vasa, 20128Resources are bound togenerated codeGenerated Codestatic final int australia=0x7f020000;R. Vasa, 20129User Interface (generally) Builtin XMLActivityView Group(Layout)Activity Class (Java)Layout Definition(main.xml)R. Vasa, 201210Provide Resources @MultipleResolutionsHighLowMediumR. Vasa, 201211Lecture Roadmap - Where arewe?• Recap• UI Construction - Separation ofConcerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources (Programatically)• Working with Alternate LayoutsR. Vasa, 201212UI Construction - Aspects toConsider• Two aspects of an application with UIPresentationPresentation FunctionalityFunctionality
    • R. Vasa, 201213UI Construction => DesignChoice• Design Choice: Do we combinepresentation and functionality (or) keepthem separated?Presentation + FunctionalityPresentation + FunctionalityPresentationPresentation FunctionalityFunctionalityR. Vasa, 201214Software Engineering Theory• Software Engineering Theory advocates,• loose coupling• separation of concernsPresentationPresentation FunctionalityFunctionalityR. Vasa, 201215Separation of Concerns inAndroidPresentationPresentation(Android)(Android)FunctionalityFunctionality(Android)(Android)Layout Definition(main.xml)Activity ClassEvent Handling, I/O ...R. Vasa, 201216Separation of Concerns in iOSPresentation (iOS)Presentation (iOS) Functionality (iOS)Functionality (iOS)View View ControllerData ModelStored in a XIB file(Built Visually)Code in Objective-CImage Source: Apple Inc. Image Source: Apple Inc.R. Vasa, 201217XML is preferred presentationlanguage• Typical GUI is interactive, but mostly static• Hence, we can code this descriptivelyMozilla (Firefox)XULMicrosoftXAMLiOSXIBOver the last decade, XML has slowly becomethe preferred approach for describing UI in arange of platformsR. Vasa, 201218XML is a (surprisingly) goodchoice• Why XML for presentation layer?• Human readable (if needed)• Machine readable (mature librariesavailable)• Schema/Syntax can be checked• Though bloated, XML can be compressed• Mozilla add-ons are just ZIP files• Apple XIB is compressed into NIB file• Android layout is compressed (fordeployment)
    • R. Vasa, 201219Lets get our feet wetR. Vasa, 201220Lecture Roadmap - Where arewe?• Recap• UI Construction - Separation of Concerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources (Programatically)• Working with Alternate LayoutsR. Vasa, 201221Demo 2 - Dealing with Buttons• Temperature Conversion (C -> F)R. Vasa, 201222What is involved?• Place some UI controls• Write a conversion function (C -> F)• When Button is clicked,• Use (C->F) conversion function• Pass it the Celsius value• Display the returned Fahrenheit ValueR. Vasa, 201223ViewsTextViewEditTextButtonTextView4 Views (UI components) using a Linear LayoutR. Vasa, 2012Common attributes of views andviewgroupsAttribute Descriptionlayout_width Specifies the width of the View or ViewGrouplayout_height Specifies the height of the View or ViewGrouplayout_marginTop Specifies extra space on the top side of the View or ViewGrouplayout_marginBottom Specifies extra space on the bottom side of the View or ViewGrouplayout_marginLeft Specifies extra space on the left side of the View or ViewGrouplayout_marginRight Specifies extra space on the right side of the View or ViewGrouplayout_gravity Specifies how child Views are positionedlayout_weightSpecifies how much of the extra space in the layout to be allocated tothe Viewlayout_x Specifies the x-coordinate of the View or ViewGrouplayout_y Specifies the y-coordinate of the View or ViewGroup24** Note that some of these attributes are only applicable when a View isin certain specific ViewGroup(s).•For example, the layout_weight and layout_gravity attributes are onlyapplicable if a View is either in a LinearLayout or TableLayout.
    • R. Vasa, 201225Linear Layout (View Group)main.xml(Layout)R. Vasa, 201226View Identifiers•We need a way to identify components thatwe created in the layout•E.g. To read input data from the field@+id TAG creates new identifiersR. Vasa, 201227Identifiers are like VariableNames4 NewIdentifiersSimilar tovariablenamesR. Vasa, 201228Restricting Input Data Type•Celsius temperature is a number•Android allows us to easily restrict the inputdata type for any fieldRestrict to signeddecimal numbersDefault ValueR. Vasa, 201229Conversion Function (C to F)•EditText (Text Field) captures String values•Conversion function works with stringsR. Vasa, 201230Handling the Button Click...• Two steps:1. Register to handle the button click2. Handle the button clickStep 1: Register to handle theclick
    • R. Vasa, 201231Handling the Button ClickAnonymous Inner Class to Handle EventStep 2: Handle the button clickR. Vasa, 201232Findings the Views• Remember: Presentation is definedexternally• So, we need to find the UI componentsbefore we can do anything with them...Get reference to the buttonReference maps to ID inlayout XML (generatedautomatically by tools inSDK)R. Vasa, 201233Finding Views..• findViewById() method is part of theActivity super classR. Vasa, 201234Short Problem 1 - Debug meAbove code is causingthe error -- what iscausing it?Hint: Code orderR. Vasa, 201235UI Interaction Handling Pattern• Component.setOn......Listener ( handler)• E.g. button.setOnClickListener (or)onTouchL..• Handler is an anonymous inner class• On...Listener handler = newOn....Listener() {}R. Vasa, 201236Views and Listeners• Android Views use a Call Back pattern• Standard Listeners (supported by all views),• OnClickListener• OnLongClickListener• OnFocusChangeListener• OnKeyListener• OnTouchListener• OnCreateContextMenuListener
    • R. Vasa, 201237Standard Listeners andCallbacks• OnClickListener ==> onClick• OnLongClickListener ==> onLongClick• OnKeyListener ==> onKey• OnTouchListener ==> onTouch• OnFocusChangeListener ==> onFocusChange• OnCreateContextMenuListener ==>onCreateContextMenuR. Vasa, 201238Mimic the pattern (for now)• When you are building app. initially, mimicthe pattern• A generic process to use (for now),• Create new project in Eclipse IDE• Adjust the layout to your needs (main.xml)• Create listeners• Call functions as needed from listenersR. Vasa, 201239A Tip for Clearer Code• Move all UI setup out of onCreate and into amethod called initializeUIKeep onCreate method as small as possibleWhy? Helps when you use Dependency Injection (more later)R. Vasa, 201240Demo C to F Convertor -ScreensR. Vasa, 201241Lecture Roadmap - Where arewe?• Recap• UI Construction - Separation of Concerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources (Programatically)• Working with Alternate LayoutsR. Vasa, 201242Orientation and ConfigurationChanges• Smart phones provide us with options toview in either landscape (or) portrait mode• The configuration of the phone can change,• Battery charger plugged-in• Slide-out keyboard is in use• Portrait ==> Landscape mode (orientation)• What are the issues when working in thiscontext?
    • R. Vasa, 201243Short Problem 2 - Zero ZeroZero?• When the app. screen rotates fromlandscape to portrait -- it reverts to default.Why?See Source code and see if you find any hint (provided with lecture notes)Start State(Default is 1 C)User Entered(45 C)Orientation Changed(Convertor reverts to 1 C)R. Vasa, 201244Android Activity Life CycleonCreate is calledwhen Activity StartsR. Vasa, 201245Android Activity Life CycleonCreate is calledwhen Activity StartsActivity isre-startedwhenorientationchangesR. Vasa, 2012Activity States1.  Active/Running state•An activity is in the front and has focus in it. It iscompletely visible and active to the user.2. Paused state•Activity is partially visible to the user but not activeand lost focus.•This occurs when another Activity is on top of this onewhich does not cover the entire screen or havingsome transparency so that the underlying Activityis partially visible.46R. Vasa, 2012Activity States• A paused activity is completely alive andmaintains its state but it can be killed bysystem under low memory when memory canbe freed by no other ways.3.  Stopped state• This is when the Activity is no longer visible inthe screen. Another activity is on top of it andcompletely obscures its view. In this state alsothe activity is alive and preserves its state, butmore likely to be killed by the system to freeresources whenever necessary47R. Vasa, 2012Activity States4. Destroyed/Dead state•An Activity is said to be dead or destroyedwhen it no longer exists in the memory. Eitherthe Activity hasn’t been started yet or once itwas started and killed by the system in Pausedor Stopped state to free resources.48
    • R. Vasa, 201249Orientation Change Re-InitialisesActivity• Orientation Change is triggered when,• User moves screen from portrait tolandscape orientation (or vice-versa)• User slides out keyboard (on some models)• Plugging phone into the charger• Orientation change causes,• Current Activity to be destroyed first• Activity is re-created and initialized againR. Vasa, 201250Activity Destroy + RecreateIssues• Private instance variables will be lost• The layout is re-initialised (includingdefaults)This is a very subtle (tricky) issueR. Vasa, 201251Activity Destroy Preserves SomeData• Android automatically preserves view state,but not the value (45 is preserved below)• Layout re-initialisation however sets defaultStart State(Default is 1 C)User Entered(45 C)Orientation Changed(Convertor reverts to 1 C)R. Vasa, 201252Activity State is PartiallyPreservedStart State(Default is 1 C)User Entered(45 C)Orientation Changed(Convertor reverts to 1 C)Default is set in value, but not the view stateR. Vasa, 201253Preserving State - Its all in the lifecycleonSaveInstanceState() is called from thisstate(State is Saved)R. Vasa, 201254Saving State (temporarily)Save the state into a “bundle”Bundle is a special data structure to store primitivesCalled by Android Runtime when Activity is Paused
    • R. Vasa, 201255Bundle stores simple stateinformationBundleBundleputString(key, value)putDouble(key, value)putInt(key, value)putStringArray(key, value[])It is a Key, Value store system(like a Hash Table or a Hash Map)Code Snippet:state.putString("inputTemperature", inputTemp);Code Snippet:state.putString("inputTemperature", inputTemp);R. Vasa, 201256We can read from a Bundle tooBundleBundlegetString(key)getDouble(key)getInt(key)getStringArray(key)Retrieval is based on the key(like a Hash Table or a Hash Map)Code Snippet:state.getString("inputTemperature");Code Snippet:state.getString("inputTemperature");R. Vasa, 201257We Retrieve State On CreationState retrievaldone hereonSaveInstanceState() is called from thisstate(Save Saved here)R. Vasa, 201258Retrieving Temporary StateonCreate -- Retrieve stateR. Vasa, 201259Lecture Roadmap - Where arewe?• Recap• UI Construction - Separation of Concerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources(Programatically)• Working with Alternate LayoutsR. Vasa, 201260Demo 2 - Display ImageResources• We can set an image to be displayed in theXML layout (simple and easy)• However, what if we want to control thisprogramatically?
    • R. Vasa, 201261Demo 2• We want to build a “Light Bulb” app.• Default -- Light Bulb is Off• On Touch -- Turn the Light Bulb on/offR. Vasa, 201262Working with Resourcesoff.pngLayout XML FileR. Vasa, 201263Working with Image Resourcesoff.pngLayout XML FileVia Java Codeon.pngR. Vasa, 201264Working with Resources• ‘getResources()’ gives us access to allresources [see API documentation]• Strings• Layout• Movie• Colour• Drawable (images)R. Vasa, 201265Lecture Roadmap - Where arewe?• Recap• UI Construction - Separation of Concerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources (Programatically)• Working with Alternate LayoutsR. Vasa, 201266Working with Alternate Layouts• When orientation changes -- defaultbehaviour is to use same layout• Ideally, we should use different layouts• The Android way,• Create two different “layout xml files”• Put one in layout (for portrait)• Put the other in layout-land (for landscape)
    • R. Vasa, 201267Portrait and Landscape LayoutsR. Vasa, 201268Lecture Recap• UI Construction - Separation of Concerns• Temperature Convertor Demo• Managing Orientation Change• Working with Resources (Programatically)• Working with Alternate Layouts