ACTIVITY, FRAGMENT, NAVIGATION - dis.uniroma1.itberaldi/MACC/05_Activity_19.pdf · •...
Transcript of ACTIVITY, FRAGMENT, NAVIGATION - dis.uniroma1.itberaldi/MACC/05_Activity_19.pdf · •...
View System• A system for organizing GUI• Screen = tree of views.
• View = rectangular shape on the screen that ‘knows how to draw itself’ wrt to the containing view
• ViewGroup: A view that contains other views
• Then views can be nested
• Support to responsive layout
• Style
Containers• Wiewgroups used to host dynamic content, or content bigger
than the available screen size (support to scroll, etc)
Containers and dynamic views• Dynamic content management requires special care to
optimize performance• content should in general be retrieved from slow source (internet)• Use a separate thread to execute content download• View elements must be added and the view re-rendered
• Very common pattern is a scrollable list of items• For this there are special views (RecyclerView)
Athoer example of containers: BarsUsed to display notification
App bar (former action bar) / toolbar
Example
(*): Credits: Deitel and Deitel, «Android for Programmers: An App-Driven Approach»
Table laoyout3,6,9 Buttons inserted programmatically
ImageView
Options
Responsive layout• The same name is repeated inside different folders, with
name layout-qualifier
layout-sw800dplayout-land..
Style/theme• «Styles and themes on Android allow you to separate the details of your
app design from the UI structure and behavior, similar to stylesheets in web design»
• «A style is a collection of attributes that specify the appearance for a single View. A style can specify attributes such as font color, font size, background color, and much more»
• «A theme is a type of style that's applied to an entire app, activity, or viewhierarchy—not just an individual view»
Recap
layoutstring..
main à /layout-sw800dp/main@string/hello à string-eng/hello
3. Mapping depends on locale setting7.0+ improved symbol resolution
hello hola ciao main.xml
3. Mapping depends on screen properties(dpi,viewport,orientation,..)
1. App refers to a symbol (eg. main)2. xml refer to symbol (eg, @/string/hello)
Introduction • An application is composed of at least
one Activity
• An activity is the controller of the GUI in the screen
• It runs inside the ‘main’ thread and it should be reactive to user’s input
• Managed by the ‘Activity Manager’
Activity
ScreenGUI
Activity and activity manager
Activity
GUI
events
user input
ActivityManager
register with
callback methods
Event response:- modify the data (model). Modify the view
Activity back stack• Activities in the system are managed via a back stack• When a new activity is created, it is placed on the top of
the stack and becomes active• The previous activity remains below in the stack until the
running activity is destroyed (for example back button)
Ak
A2A1
Running activity
Task, Process, Thread• The set of activities lunched by a user is a Task• Each application runs inside its own Process• All the components of an app runs inside the only created
thread (the main thread)• Howver, usually other threads are created to peform long
running operations (either explicitally or through other components, e.g., services)
• The activity in a task can belong to different application and run in a different processes • For example picking a contact will lunch the ‘contact’ application,
Activity and Process
Note: a process holding paused activities is not necessarily killed
hint: The OS provides the app the chance to trimmermemory usageimplement this callback method (onTrimmer…) to reduce the need for the OSto kill the process Note OS kills the entire process not a single activity
Activity lifecycle• Each activity in an application
goes through its own lifecycle: it responds to a set of methods called by “android”
• Once and only once when an activity is created, is the onCreate(…) method executed
• If the activity exits, the onDestroy() method is executed
• In between, various methods are called allowing the activity to be harmonically managed
Lifeclye interleaving..• I/INFO�A: onCreate• I/INFO�A: onStart• I/INFO�A: onResume (second acivity is lunched an takes all the screen)
• I/INFO�A: onPause• I/INFO�B: onCreate• I/INFO�B: onStart• I/INFO�B: onResume• I/INFO�A: onSaveInstanceState• I/INFO�A: onStop (First activity is no longer visible)
• I/INFO�B: onPause (back button is now pressed)• I/INFO �A: onRestart• I/INFO �A: onStart• I/INFO�A: onResume• I/INFO�B: onStop• I/INFO�B: onDestroy
onPause method• Called when the system is about to
start resuming another activity.
• This method is typically used to commit unsaved changes to persistent data, stop animations, threads, and any thing that may be consuming CPU, and so on.
• It should do whatever it does very quickly, because the next activity will not be resumed until it returns
• OnResume: it'good place to begin animations
Activity lifecycle: save state
• à onPause• à onSaveInstanceState• à onStop
• à onRestart• à onStart• à onRestoreInstanceState• à onResume
State saving via viewModel• Using a bundle (and
onSave/onRestore) is goof forsmall data that can be serializedthen deserialized
• It is not efficient for potentiallylarge amounts of data like a list of users or bitmaps
• Android provides a way to persistlarge amonunt of data amongthrough the lifeclyce usingViewModel
Recap: states of an activity • Running: the activity is in foreground and has the focus
• All events are delivered to it
• Paused: it is partially visible, but lost the focus • For example the foreground activity doesn’t occupy the whole
screen (there is a dialog box in foreground)• A paused activity maintains all state and member information, but
the system can kill it
• Stopped: the activity is completely obscured by another one
Recap: state of an activity
• In the Paused or Stoppedstate an activity can be killed when resources are needed
ActivityLifecycle (demo)
I/INFO� A: onCreateI/INFO� A: onStartI/INFO� A: onResume (Button is clicked)
I/INFO� A: onPauseI/INFO� B: onCreateI/INFO� B: onStartI/INFO� B: onResumeI/INFO� A: onSaveInstanceState (now the activity can be killed…)
(back botton is pressed)
I/INFO�B: onPauseI/INFO�A: onResumeI/INFO�B: onStopI/INFO�B: onDestroy
note method calls are interleaved
android:theme="@android:style/Theme.Dialog"
How an activity is created (explicitally)?• An activity is created if it is the target of a special
message called Intent
• An activity A starts another activity B by creating an explicit Intent with target B
• Uses a special method• Context.startActivity(intent)
How an activity is created (implicitally)?• An activity declares to the system its ability to perform
‘actions’ through an intent-filter (declared in the manifest)
• The calling activity creates and intent with the action
• The activity manager presents a list of all activities thatmay perform the action (if more than one)
ActivityManager
Activity A Activitystart(…)
Action?
Fragments• Useful for large screen (like tablet)• or as navigation tools• Fragments are hosted inside an Activity
• A fragment is ‘attached’ to a View• It must create its view (from an XML file)
• Fragments have their own lifecycle (which is more complex than the activity)
• Can be added via XML file or programmatically
Fragments and Activities
CVFragment A
CVFragment B
Activity
Activity’slifecycle methods
Fragment specificlifecycle methods
FragmentManager
getActivity()
Fragment via XML
LinearLayout<fragment
android:name=«….»>
<fragmentandroid:name=«….»>
implementationFragment Code
Fragment Code implementation
Activity Code implementation
Inflates activity_main.xml
activity_main
Inflates firstFragement.xml(onCreateView)
Extends a ListFragment
Fragments added programmatically• Use a FragmentManager to add, remove fragments. • After changes, use commit
activity_main
FrameLayout, id=1
FrameLayout, id=2
placeholder(fragment container)
Wireframe/Storyboard/Navigation• At design time, one screen is mocked as a wireframe• A screen is generally an implementation on one or more User Stories• The whole behaviour of an application is best described as a
‘storyboard’ (relationship among wireframes)• The way a user can ‘move’ inside the app is called navigation
Navigation support in android (experimental)
https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing
2D Graphic: extending a View• User can define its own View to draw specific graphical
objects on a Canvas • Canvas are used to draw a Bitmap• This is achieved extending the View class
• The system provides the canvas when it calls onDraw(Canvas c)method implemented by the class that extends View
• This is good for infrequent updates (no additional thread is required)
MotionEvents• Created when fingers touch the screen or move• Delivered to the appropriate listener• In case of complex movements they generate a gesture
• A motion event contains• Action Code (state change that occurred)
• UP,MOVE,DOWN• Action values
• Position, time, etc-
Multitouch• The screen is sensible to multiple touches at the same
time• Each finger is called a pointer and it receives a unique ID
as long as it is active• Touch events from different fingers are grouped together
inside a single MotionEvents object • Each pointer gets an index within the event (may change
over time) which is not the same of the pointer ID• It is used as index to data structure to get specific data
Some Action Code• ACTION_DOWN
• The first finger touches the screen
• ACTION_POINTER_DOWN• Another finger touches the screen
• ACTION_POINTER_UP• One of the finger doesn’t touch the screen anymore
• ACTION_MOVE• Some finger moves
• ACTION_UP• The last finger leaves the screen
Some method• getActionMasked()
• The the action associate to the event
• getAction()• The action code AND the pointer
• getActionIndex()• The index of the finger the caused the action
• getPointerCount()• Number of pointers associated to the event
• getX(..),getY(..)
2D Graphic: SurfaceView and animation• The other option is to extend SurfaceView
• Used for fast movement• Application gets a reference to a Surface, which is a low-level
drawing area • In addition, programmer should provide a secondary thread inside
which drawing operations are performed• The class should implement the SurfaceHolder.Callback
Interface• Define lifecycle methods called when the surface changes• Setup: the view’s getHolder() method must be called. It returns a
SurfaceHolder• In addition, callbacks methods should be registered using the addCallback() SurfaceHolder’s method
Surface• The lifecycle of a Surface is determined by the following 3
methods (called from the GUI thread):• surfaceCreated(…)• surfaceChanged(…)• surfaceDestroyed(..)
• To draw on the surface its required to:• Acquire a lock on the underlying canvas object
• SurfaceHolder.lockCanvas()• Draw
• Canvas.drawBitmap()• Unlock the canvas
• SurfaceHolder.unlockCanvasAndPost()
Animation: Property animation• Programmatically or XML file• Creates an animation by modifying an object’s property
values over a set period with an Animator• ObjectAnimator:
• set the value of a property of an object• Uses an interpolator to determine the amount of animation at a
given time• Using XML file the android:PropertyName attribute corresponds to
a setName method implemented in the object
Animation: View animation• Tween animation
• Creates an animation by performing a series of transformations on a single Image with an Animation• Resizing, rotation, translation,alpha
• Frame by frame animation• Shows a sequence of images in order with an AnimationDrawable