ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi
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
Example of views hosts a static image.. a web page (used for mobile web app) a video
Example of views Calendar view
Layouts Wiewgroups used to host other views Constrained and Linear are the most used
Layouts example Each View: H=matchParent W=matchParent Weigth=1 B1 B2 B3 B4
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: Bars Used to display notification App bar (former action bar) / toolbar
Example Options ImageView Table laoyout 3,6,9 Buttons inserted programmatically (*): Credits: Deitel and Deitel, «Android for Programmers: An App-Driven Approach»
Object view representation activity_main.xml layout name 3434 id button 233 R
Responsive layout The same name is repeated inside different folders, with name layout-qualifier layout-sw800dp layout-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 view hierarchy not just an individual view»
Theme Editor (android studio)
Multilanguage support
Recap 1. App refers to a symbol (eg. main) 2. xml refer to symbol (eg, @/string/hello) 3. Mapping depends on locale setting 7.0+ improved symbol resolution 3. Mapping depends on screen properties (dpi,viewport,orientation,..) @string/hello à string-eng/hello main à /layout-sw800dp/main string.. layout hello hola ciao main.xml
Material design https://material.io/
Introduction Screen GUI An application is composed of at least one Activity An activity is the controller of the GUI in the screen Activity It runs inside the main thread and it should be reactive to user s input Managed by the Activity Manager
Activity and activity manager user input Event response: - modify the data (model). Modify the view GUI events Activity register with Activity Manager callback methods
Activity and user navigation
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) Running activity Ak A2 A1
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 trimmer memory usage implement this callback method (ontrimmer ) to reduce the need for the OS to 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
Activity lifecycle Create-destroy path The arrow is the path of Activity 2
Activity lifecycle Visible-Unvisible-Visible The arrow is the path of Activity 1
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
Activity lifecycle Visible-Partially_visible- Visible path
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 Why to save the state?
State saving via viewmodel Using a bundle (and onsave/onrestore) is goof for small data that can be serialized then deserialized It is not efficient for potentially large amounts of data like a list of users or bitmaps Android provides a way to persist large amonunt of data among through the lifeclyce using ViewModel
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 Stopped state an activity can be killed when resources are needed
ActivityLifecycle (demo) android:theme="@android:style/theme.dialog" I/INFO A: oncreate I/INFO A: onstart I/INFO A: onresume (Button is clicked) I/INFO A: onpause I/INFO B: oncreate I/INFO B: onstart I/INFO B: onresume I/INFO A: onsaveinstancestate (now the activity can be killed ) (back botton is pressed) I/INFO B: onpause I/INFO A: onresume I/INFO B: onstop I/INFO B: ondestroy note method calls are interleaved
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 that may perform the action (if more than one) Activity A start( ) Activity Action? Activity Manager
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 Activity Fragment A CV Fragment CV B getactivity() Activity s lifecycle methods Fragment specific lifecycle methods Fragment Manager
Fragment lifecycle
Using Fragments
Fragment via XML activity_main LinearLayout <fragment android:name=«.»> implementation Fragment Code Inflates firstfragement.xml (oncreateview) <fragment android:name=«.»> Fragment Code implementation Extends a ListFragment Activity Code implementation Inflates activity_main.xml
FragmentProgram (demo)
Fragments added programmatically Use a FragmentManager to add, remove fragments. After changes, use commit activity_main FrameLayout, id=1 placeholder (fragment container) FrameLayout, id=2
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 patterns
An example
Example of navigation
Navigation drawer 1.Icon in app bar 2.Header 3.Menu items
Navigation support in android (experimental) https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing
Android Navigation
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(..)
Example (MotionEvent)
Example (SimpleDraw)
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()
Surface Example
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
Property animation (demo)
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
TweenAnimation (demo)
QUESTIONS?