Topic 4: User Interfaces Part 2
(Author: Dr. Caspar Ryan, Mr. Keith Foster)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 1
Assignment
• After this lecture you have all you need for assignment 1
– Fundamentals, components, lifecycle etc.
– UI views, layouts and widgets
– Today :
• Events, listeners, etc.
• Dialogs, notifications, menus, action bar etc. • ListView/RecyclerView
– https://developer.android.com/guide/topics/ui/
• Next week coding workshop
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 2
•
Android has a similar (though simpler) event handling mechanism to Java AWT/Swing
– Event sources (View)
– Event listener (inner) classes (e.g. View.OnClickListener)
– Register listener with source with View.setOnXYZListener(View.OnXYZListener listener)
– Event handler methods [e.g. public abstract void onClick(View v)]
– Event Object [e.g. android.view.KeyEvent]
– NOTE: some event handler methods have no event object or primitive parameterse.g.OnFocusChangeListener.onFocusChange(View v, boolean hasFocus) ]
The basic in-built listeners defined as nested classes/interfaces of the View class
– e.g. View.OnClickListener
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 3, Slide 3
•
Event Handling
Event Handling (contd.)
• Someclassesincludingandroid.view.Viewhavetheir own built in Event Handler methods [e.g. View.onKeyDown(int, KeyEvent)] that are called automatically
• SpecialXMLcaseforhandlingstandardclicks – XML attribute (of View) e.g.
android:onClick=”myOnClickEventHandler”
– Must define public void myOnClickEventHandler(View v) intheContext (usually an Activity)
– NOTE: Increases coupling between XML and Java => may reduce maintainability, reusability etc.
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 3, Slide 4
Forwarding/Consuming Events
• Some event handler methods return boolean state e.g. boolean OnLongClickListener.onLongClick(View v)
• This signifies whether the event was handled (consumed)
• i.e. return true means event was handled an no further
processing by parent Views
• return false if you want other components to handle the event
• this is based on the composite nature of Views/ViewGroups where events are passed up the containment hierarchy
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 3, Slide 5
Common Listener Classes
View.OnAttachStateChangeListener
Interface definition for a callback to be invoked when this view is attached or detached from its window.
View.OnClickListener
Interface definition for a callback to be invoked when a view is clicked.
View.OnCreateContextMenuListener
Interface definition for a callback to be invoked when the context menu for this view is being built.
View.OnDragListener
Interface definition for a callback to be invoked when a drag is being dispatched to this view.
View.OnFocusChangeListener
Interface definition for a callback to be invoked when the focus state of a view changed.
View.OnGenericMotionListener
Interface definition for a callback to be invoked when a generic motion event is dispatched to this view.
View.OnHoverListener
Interface definition for a callback to be invoked when a hover event is dispatched to this view.
View.OnKeyListener
Interface definition for a callback to be invoked when a key event is dispatched to this view.
View.OnLayoutChangeListener
Interface definition for a callback to be invoked when the layout bounds of a view changes due to layout processing.
View.OnLongClickListener
Interface definition for a callback to be invoked when a view has been clicked and held.
View.OnSystemUiVisibilityChangeListener
Interface definition for a callback to be invoked when the status bar changes visibility.
View.OnTouchListener
Interface definition for a callback to be invoked when a touch event is dispatched to this view.
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 6
Gestures/Scaling
• In addition to the View inner classes there are a number of standalone listeners
• android.view.GestureDetector
• android.view.ScaleGestureDetector
• Detects various gestures and events using the supplied MotionEvents
• Create an instance of the GestureDetector and/or
ScaleGestureDetector for your View or Activity
• Register GestureDetector.OnGestureListener and/or
ScaleGestureDetector.OnScaleGestureListener callbacks on the
detector(s)
• There is also an extra GestureDetector.OnDoubleTapListener class
• In the View or Activity onTouchEvent(MotionEvent) method you
forward to onTouchEvent(MotionEvent) in the detectors.
• The methods defined in your listeners will be called accordingly
• See https://developer.android.com/training/gestures/detector.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 7
Dialogs
• android.app.Dialog is the base class for all dialogs
• Generally use (or modify) the following subclasses:
– AlertDialog, CharacterPickerDialog, DatePickerDialog, TimePickerDialog, ProgressDialog
• In API < 14 a Dialog is associated with an Activity.
– Create dialogs in Activity.onCreateDialog(int)
– Requires switch statement but can be delegated to another class for better cohesion
– Dialogs are created and pooled (i.e. cached) so you can modify contents prior to display inActivity.onPrepareDialog(int, Dialog)
– call Activity.showDialog(int) pass a unique integer identifying the dialog
– Dialogs generally dismiss themselves with Dialog.dismiss() but can be closed
externallywithActivity.dismissDialog(int id)
• Most common Dialog type is AlertDialog which is the superclass for DatePickerDialog, TimePickerDialog, ProgressDialog
– Use nested class AlertDialog.Builder class to configure the Dialog
– See API and code sample for details
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 8
AlertDialog
1. Title This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you need to state a simple message or you might not need a title.
2. Content area This can display a message, a list, or other custom layout.
3. Action buttons There should be no more than three action buttons in a dialog.
The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with several variations. See API example and Caspar’s refactored code in Topic 4 source
Some style guidelines here
https://material.io/guidelines/components/dialogs .html
NOTE: Ok/Cancel button order changed to Cancel/OK in API 14+
From https://developer.android.com/guide/topics/ui/dialogs.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 9
DatePicker and TimePicker
From https://material.io/guidelines/components/dialogs.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 10
Dialog API Sample
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 11
DialogFragment
• In API 14 and above the Activity dialog methods are deprecated in favour of using fragments (Use a DialogFragment instead)
• Dialog code is unchanged just the launching and management mechanism
• DialogFragment decouples responsibility of managing dialogs from
Activity
– one to one mapping between a DialogFragment and a Dialog
– override DialogFragment.onCreateDialog() for custom dialogs
– removes need for switch statement for improved cohesion and code clarity
• Use DialogFragment.show(...) method to display a Dialog and manage the back stack
• Can add as part of a FragmentTransaction to use as a standard fragment instead of a separate dialog
FragmentTransaction ft = getFragmentManager().beginTransaction(); DialogFragment newFragment = MyDialogFragment.newInstance(); ft.add(R.id.embedded, newFragment);
ft.commit();
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 12
Notifications
• Applications often need to periodically notify the user even when the application isn’t in the foreground
• Applications can notify users with text, vibration, LED, lights and audio
• e.g. new email/message, contact signs in/out, stock/auction updates,
news/weather updates etc.
• Use notification sparingly (and user configurable)
• Make notification style appropriate for the significance of the alert (i.e. avoid sirens, flashing lights etc. unless really important!)
• Devices do not necessarily support all notification styles/types
• The status bar (notification area) typically shows ongoing information
such as date/time, battery charge status, telephony and connectivity state etc.
• It can also display periodic notifications (like incoming messages)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 13
Notification Version Evolution
• Starting in Android 5.1 (API level 22) users can disable specific notification types on a per app basis
• Starting in Android 7.0 (API level 24), users can respond directly to text messages or update task lists from within the notification dialog (see first ref link on slide 18)
• Starting in Android 7.0 (API level 24), Android also provides developers with a new way to group: bundled notifications (see first ref link on slide 18)
• Starting in Android 8.0 (API level 26), Notifications are assigned to channels which gives finer user control granularity than per app (via settings in Android)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 14
Notification Drawer
• Opening (dragging) the status bar shows the notification drawer which is an ordered notification list with more information (and clear options)
– Small* and large icons (appears on status bar and full notification)
– title text* (appears in full notification)
– content text* (appears in full notification)
– ticker text (used to go in status area but now used for accessibility)
– one or more intents for different interactions (launches if the user clicks, swipes, dismisses etc.)
– expanded notification layout
– progress indicator
– notifications have a priority
– *isrequired
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 15
Creating Notifications
• Basis for notification is the android.app.NotificationManager class
– NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
• Individual notifications are instances of the android.app.Notification class
– DeprecatedConstructor:Notification(int icon, CharSequence tickerText, long when)andmethod
Notification. setLatestEventInfo(Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) (DeprecatedasofAPI11+, REALLY deprecated as of API23 .. i.e. deleted!)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 16
Creating Notifications (contd.)
• Therefore use Notificaton.Builder or NotificationCompat.Builder classes instead
– passed to the NotificationManager.notify(int id, Notification notification)ornotify(String tag, int id, Notification notification) method
– See Caspar’s refactored notification examples in Topic 4 source code
• NOTE: See the use of the PendingIntent class for allowing the notification manager to launch an intent on the original application when a notification is selected/activated
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 17
Notifications (references)
• https://developer.android.com/guide/topics/ui/notifiers/notifications.html for details of setting notification sounds, vibrations etc.
• https://material.io/design/platform-guidance/android-notifications.html for design guidelines for notifications
• https://developer.android.com/guide/topics/ui/notifiers/toasts.html for using android.widget.Toast which is a simpler form of notification
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 18
API Notification Sample
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 19
Options Menu
• An options menu appears when the user presses the device or on screen menu button
– Menu hardware button no longer required as of API 11+ but functionality remains
• Conceptually similar to pull down menus in desktop (e.g. AWT/Swing)
applications
• Menus are defined in the /res/menu directory using a specific xml format
withone