代写 html android Java XML Topic 4: User Interfaces Part 2

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

perfilecontainingmultiple elements
• Menu XML must be “inflated” into memory using android.view.MenuInflater in an activity’s Activity.onCreateOptionsMenu(Menu) method
• Similar to Dialog, you can update the menu every time it is displayed (e.g. add/remove/enable/disable items) using Activity.onPrepareOptionsMenu(Menu)
• The simplest use is to add an Intent to each using MenuItem.addIntent(Intent) which will automatically start an activity when the menu item is selected
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 20

Options Menu (contd.)
• For more specific menu responses override Activity.onOptionsItemSelected(MenuItem)
• Menus can be nested (android.view.SubMenu) by including a

element withinan (onlyonelevelofnestingandsubmenusdonotsupporticons)
• Menu items can grouped using the element which is particularly useful for checkable items e.g.

– Check state must be programmatically managed in onOptionsItemSelected()
– See API and code example for details
• The Android system automatically manages large menus depending upon version
– e.g. old Android versions up to 10 can display a maximum of six items before an overflow menu item appears (signified by the “more” option)
– managed by the ActionBar in API 11+
• Menus are useful for operations that are used less frequently or where there exist many options and it would be inconvenient to spread them over many screens for direct access
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 21
Options Menu and Fragments
• Options menus are added to Fragments in the same way as an Activity (the same methods are used and overridden)
– supported for both options and context menus
• If both your activity and fragment(s) declare items for the options menu,
they are combined in the UI
• The activity’s items appear first, followed by those of each fragment in the order in which each fragment is added to the activity
• Can re-order the menu items with
the android:orderInCategory attribute in each you need to move
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 22

Options Menu Example
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 23
Context Menus
• A context menu appears when the user long presses a View (common usage is an individual child item in a ListView)
• Conceptually similar to popup menus in desktop (e.g. AWT/Swing) applications but do not allow icons, submenus, or shortcuts
• Context menus are defined in /res/menu in the same way as options menus
• Context menus are “inflated” using the
Activity.onCreateContextMenu(Menu) method
• MenuItem and Intent is used the same way as with options menus using the
method Activity.onContextItemSelected(MenuItem)
• A View within an Activity that should trigger a context menu must be
registered with Activity.registerForContextMenu(View);
• Context menus are used in much the same way as Options menus but where the
options apply to a specific item (rather than the whole activity)
• May not be obvious to (i.e. discovered by) users so consider them a shortcut but
not sole means of interaction (see Contextual Action Bar as an alternative)
• Same methods on Fragment class and see also contextual action bar on slide 30
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 24

Context Menu Example
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 25
ActionBar (or App Bar)
• Introduced with Honeycomb (API 11) to provide consistent user actions and navigation modes across applications
– system automatically adapts the action bar’s appearance for different screen configurations
• Displays option menu items as actions or in an overflow menu (default behaviour)
• Originally Provides tab functionality but deprecated at API 21
– can use FragmentTabHost instead (see topic 3 examples)
• Provides a dedicated space for identifying the application brand and user location
• Provides a number of mechanisms for switching application views
• Contextual action bars can be displayed for context specific actions
• For many apps it is a primary method of navigation (in addition to
DrawerLayout .. navigation draw)
• https://developer.android.com/training/appbar/
• https://material.io/design/components/app-bars-top.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 26

AppBar Components
from https://material.io/design/components/app-bars-top.html
An Action Bar/App Bar can contain different components but the material design guidelines
recommend the following for consistency:
1. Container – The activity
2. Navigation Icon (optional) – Can be a menu icon (which opens a navigation drawer), an up
arrow to navigating up an app’s hierarchy, or a back arrow to return to previous screen
3. Title (optional) – e.g. app name or screen/section title where navigation is relevant
4. Action Items (optional) – app actions move in and out of the overflow menu depending on
width
5. Overflow Menu (optional) – app actions move in and out of the overflow menu depending
on width
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 27
Using the ActionBar
• Must set minSdkVersion to >=11 or use compatibility libraries (see topic 3 source code)
• Shown by default when targetSdkVersion>=11 but can hide
with appropriate theme e.g.:

• Can show or hide programmatically with ActionBar.show()/hide()
• Use menu resource definition to determine if an OptionsMenu should appear in the ActionBar e.g. android:showAsAction=”ifRoom”
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 28

Using the ActionBar (contd.)
• Use SpinnerAdapter (slide 32), ActionBar.OnNavigationListener,
ActionBar.setNavigationMode() and ActionBar.setListNavigationCallbacks()
– deprecated .. see mad.topic4.actionbar.NavActionBarActivity example for alternative approach
• For split action bar
add uiOptions=”splitActionBarWhenNarrow” to your or manifest element
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 29
Contextual Action Bar
• ForAPIlevel>=11andthecurrentmaterialdesign, the contextual action bar is preferred over floating context menus
• Toprovidecontextualactionsyoushouldinvokethe
contextual action mode upon one of two View events
(or both):
– The user performs a long-click on the view
– The user selects a checkbox or similar UI component within the view
• Forcontextualactionsonindividual,arbitraryviewsor
items
– implementtheActionMode.Callbackinterface
– call Activity.startActionMode(ActionMode.Callback cb)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 30

Contextual Action Bar (contd.)
• Forcontextualactionsongroupsofitems (e.g. ListView or GridView)
– call AbsListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODA L)
– implement AbsListView.MultiChoiceModeListener
– call AbsListView.setMultiChoiceModeListener(
AbsListView.MultiChoiceModeListener l)
• Is based on menu resources so code is similar
• See mad.topic4.menu.refactored.actionbar example
• https://developer.android.com/guide/topics/ui/menus.html
• Also see android.widget.ToolBar added in API 21 and
mad.topic4.actionbar.NavActionBarActivity example
• https://developer.android.com/training/design-
navigation/index.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 31
AdapterViews and Adapters
• An android.widget.AdapterView has an android.widget.Adapter which maps from a data source to child components of an AdapterView
• The Adapter is responsible for creating the child components from a resource id (which usually maps to an XML layout file)
• The appropriate concrete AdapterView classes e.g. Spinner or ListView have a setAdapter(…) method which takes the appropriate
type e.g. ListView.setAdapter(ListAdapter adapter) or Spinner.setAdapter(SpinnerAdapter adapter)
• The default Adapter implementations e.g. ArrayAdapter and SimpleCursorAdapter* implement both SpinnerAdapter and ListAdapter interfaces (so can be used with multiple View types)
• can add simple hard coded string array in XML without Adapter using android:entries=”@array/some_array”
• * See Topic 6 Data and Persistence Management
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 32

AdapterViews and Adapters (contd.)
• ArrayAdapter maps data to either:
– asimpleTextView
– a TextView within a larger Layout
– orarbitraryViewswithinaViewGroupbyoverridingView ArrayAdapter.getView(int position, View convertView,
ViewGroup parent)
– In all three cases a separate View is created for each data item
– displaypositionisbasedontheindexoftheunderlyingList(since
java.util.List is zero indexed)
– see AdapterView.OnItemClickListener and
AdapterView.OnItemSelectedListener for responding to interaction
• Can be used with context menus by using
Activity.registerForContextMenu(View view)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 33
AdapterViews and Adapters (contd.)
• CheckwhichitemintheAdapterViewinitiatedthe
context menu using ContextMenuInfo MenuItem.getMenuInfo()
– willreturnanAdapterContextMenuInfoobjectforAdapterView instances such as ListView
• *SeepreviousmenuexampleforSpinnerand ListView code
• SeeAPIforfulldetailsofinheritancehierarchiesand relationships
• ThereisalsothenewerRecyclerViewclasswhichis a more powerful list style view but you can use simpler ListView for assignment
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 34

RecyclerView
• A more powerful version of ListView (added in API 22)
• Based on the holder pattern introduced to optimise ListView
scrolling https://developer.android.com/training/improving-
layouts/smooth-scrolling.html#ViewHolder
• You create both a RecyclerView.Adapter AND a RecyclerView.ViewHolder (often as an inner class) as part of required usage
• Includes default animations and dedicated RecyclerView.LayoutManager implementations (e.g. LinearLayoutManager) but you can create your own
• https://www.raywenderlich.com/126528/android- recyclerview-tutorial
• Can support swipe/drag using android.support.v7.widget.helper.ItemTouchHelper
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 35
RecyclerView
• Create a custom item XML layout for your RecyclerView to use for its items
• Declare the RecyclerView in an activity/fragment layout
and reference it in your activity/fragment Java file.
– Attach an adapter to the RecyclerView (see below)
– Attach a layout manager (which implements RecyclerView.LayoutManager)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 36

RecyclerView
• Create a RecyclerView.Adapter and override
– onBindViewHolder(ViewHolder holder, int position)
– (must call your custom ViewHolder.bind() method (see next slide))
– onCreateViewHolder(ViewGroup parent, int viewType)
– creates a ViewHolder (so it uses your overridden constructor .. see next slide) and passes it an inflated View of appropriate custom layout
– getItemCount()
– add extra methods to add/remove, clear etc. by forwarding to supporting data
structure such as simple JCF Collection (ArrayList etc.)
– call notifyDataSetChanged() or notifyItemRangeChanged()
when underlying data changes
– to more efficiently update from a backing model you may wish to use the DIffUtil class
– https://developer.android.com/reference/android/support/v7/util/DiffUtil
– NOTE: you have to manage your own indexing unlike ArrayAdapter!
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 37
RecyclerView
• CreatetheRecyclerView.ViewHolder for your view items (can be inner class to reference underlying data from Adapter)
– intheconstructoryoudofindBy..callstostoretheViewrefsof the passed item layout
– alsowriteacustombind() method(thisisnotbasedonan interface so can be arbitrarily named) which can be called to populate the Views
– are responsible for their own event handling (or can delegate to individual components in the item view)
– NOTE: if you need adapter position for any custom listeners you can attach the listeners here, taking care to remove existing listeners from previous binds if necessary! (only addXYZListener() not setXYZLister())
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 38

Summary


UI development in Android requires the integration of a number of elements
– Component/Activity/Fragment lifecycle (details on threading in Topic 5)
– View and ViewGroup classes
– Layout management
– Event handling
– Dialog, Menu, Notification, ActionBar
– Adapter and AdapterView to populate multi-item widgets
– Manifest and XML resources (and supporting files such as icons etc.)
As much as possible the UI should be specified declaratively (XML) but some functionality must be implemented programmatically e.g.
– Changing the attributes of a View at runtime
– Changing the contents of a Dialog or Menu before it is displayed
– Specifying content for a Notification
– Adding an Intent to a MenuItem
– Adding listeners other than OnClickListener (which can be added
declaratively)
– Adding components to an ActionBar
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 4, Slide 39