FIT2081 Notes
Week 1: Terms and Introduction to Mobile Applications
Software Development Kit (SDK) – Bundle of all the software components to develop and deploy on a platform. We use Java SDK and Android SDK.
Application Programming Interface (API) – The class library by which we can call (execute) to perform common but complicated tasks. This gets constantly updated and thus, improves with increasing capabilities and updates by levels.
Integrated Development Environment (IDE) – Software environment that supplements all the tools developers need to develop applications. E.g. debuggers, version control, language sensitive code editors. We use Android Studio.
There are 3 different types of Mobile Apps which have different capabilities, advantages and disadvantages.
Native Apps
o App’s compiled code are developed specifically for 1 type of OS e.g. iOS, Android
o Built using the SDK tools and languages provided by the platform vendor 1. AndroidStudiousingJava
2. Swift with XCode IDE for iOS
o Apps are managed and downloaded via the app store (Play, Apple Store)
Mobile Web Apps
o Internet-enabled apps accessible via mobile device’s browser.
o Users don’t need to download or install the app to access it.
o Can be used for all device OS, written in HTML, CSS, and interaction in JS or
Jquery etc.
o New technologies keep developing to create new possibilities for what a Mobile
Web App can do
1. E.g. latest is Service Workers, which allow push notifications to a Mobile Web
App, something previously only possible on a Native App.
Hybrid Apps
o Written using additional language and development environments other than the recommended languages for the platform.
o Still deployed as a Native App.
o Tries to get the pros of both Native and Mobile Apps without their cons
Comparisons between App Types
Native Apps PROS
✓ Access to all native API’s
✓ Faster graphics performance
✓ AppStore distribution – security
✓ can be used offline, access
anytime
✓ Can store info locally
Native Apps CONS
✓ Must be written for each platform so higher development + maintenance costs
✓ Tedious to get app approved on App store + costly
Mobile Web Apps PROS
✓ Cross-platform affinity
✓ Cheaper to develop + maintain
✓ Fast Centralized updates (don’t need
to wait for approval)
Mobile Web Apps CONS
✓ Limited Features as no access to native API
✓ Many variations between mobile browsers
✓ Cannot use offline
✓ No quality control of app = more
unsafe
Hybrid Apps
1. Cross-platformaffinity
2. Writtenwithwebtechnologies(HTML5,CSS3,JS)
3. Runs locally on the device, supports offline
4. Access to native API’s
5. AppStoredistribution
Summary
1. All 3 types are thriving in their own way
2. A poorly designed app is bad no matter how its implemented
3. Design requirements for a Mobile App is very different in comparison to a
desktop App.
We stick with Native Apps in this unit because:
1. Free,rocksolidIDEwithgooddeviceemulations
2. Web Apps and Hybrid Apps are in a state of uncertainty as the technologies
they depend upon rapidly evolve
We use the Android Mobile App Platform because:
1. Highestdevicecount
2. Javaisthemostcodedlanguageintheworld,consideredanindustry
standard
App Basics
All our Activities must extend Activity or AppCompatActivity AppCompatActivity provides backwards compatibility in our app. List 3 tasks we must do in the onCreate () callback of our activity
1. Call super.onCreate()
2. Inflate our layout in the layout file by calling:
setContentView(R.layout.our_layout_file)
3. Retrieveanydatainsidethebundle(ifany)
Note: We must first inflate our layout before referencing any widgets in our layout.
Week 2: Android Components, API Levels, Fragmentation, and Backward/Forward Compatibility
Android is an open source Linux-based OS designed for touchscreen mobile devices.
It is maintained by Google who has the largest Android App store called Google Play.
OS is a collection of software that manages computer hardware resources and provides common services for computer programs.
Android Versions
1. SDKPlatform
• Includes the version of the
framework API
• Incremented using n.n.n format
2. APILevel
• Integer value which uniquely
identifies the API revision offered by a version of the Android platform.
3. APICodename
• Given whenever there is a major
platform release
• Named after desserts and are
incremented alphabetically
Selecting the correct SDK version
You ideally want to target as many people as possible, however targeting low SDK levels has disadvantages such as lack of features.
Your choice of minimum SDK level should be a trade-off between the distribution of users to target, and the features your application will need.
Android Fragmentation – concerns with the alarming number of different Android OS versions in the market
Big problem as Android updates are slow to reach actual devices due to:
1. CustomisationofAndroidforadevice
2. Customisation of Android interface and apps by device manufacturers and
T elcos
3. Reluctance by manufacturers to spend time and money customising Android
for older devices which would allow users to delay buying new devices
Forward Compatibility – Old apps running on newer platform versions
Android applications are generally forward compatible with new versions of the Android platform, because almost all changes to the framework API are additive.
Rare case something goes wrong is when the application uses a part of the API that is later removed for some reason.
Backward Compatibility – New apps running on older platform versions
Android applications are not necessarily backward compatible with older versions of the Android platform as the App can utilize new framework APIs, which provide new platform capabilities, or replace existing API parts.
Android Support Library
Official Library providing a backward compatibility layer for earlier versions of Android devices. Main function is to provide some important newer APIs to run on older devices.
The Library also provides additional convenience classes and features not available in the standard Framework API for easier development and support across more devices.
Library has been extensively developed and is now considered an essential resource for app development.
Android App Components
1. Activities are the UI and logic of the app and defines a single window in the UI. There can be multiple activities in an app, and they can run together to bring a cohesive user experience.
✓ Activities have Lifecycles which we’ll see later in Week 3.
✓ An activity can start another activity in the form of Intents (see later).
2. Services–processesthatruninthebackgroundanddonothaveauser interface. Can be initialized and managed from Activities, broadcast receivers, or other services. Ideal for situations where an app needs to continue running tasks but does not need a visible UI, e.g. music player.
3. Content Providers – Class which implements a mechanism for the sharing of data between applications. An app can provide other app’s access to its data through a Content Provider, with access provided via a URI (see Week 7-8). They essentially provide an abstraction from the app and its underlying data source.
4. Content Resolver – the single, global instance in your application that provides access to your (and other Apps) content providers. It accepts requests from clients and resolves these requests by directing them to the content provider with a distinct authority. Does this by storing a mapping from authorities to Content Providers.
5. Broadcast Receivers – the mechanism by which Apps can respond to Broadcast Intents. The receiver operates in the background and do not have a UI. A Broadcast Receiver must be registered by an application and configured with an Intent Filter to indicate the type of broadcast in which it is interested. When a matching intent is broadcasted, the receiver will be invoked by the Android runtime by which it will then have 5 seconds to complete any tasks required of it (e.g. launching a service, making data update, and issue notification) before returning.
6. Intents–Mechanismwhichimplementtheflowthroughactivities,binding individual components to each other at runtime. Intents activate 3 of 4 component types – activities, services, and broadcast receivers.
Defining an Intent takes two parameters: the current Activity Context, and the target Activity.
Activity Intents – The mechanism by which one activity can launch another activity or service and implement the flow through the activities that make up an application; Can be defined:
1. Explicitly – request the launch of a specific activity by referencing the class name 2. Implicitly-statingthetypeofactiontobeperformedorprovidingdataofa
specific type. This lets Android runtime choose an appropriate target Activity to activate.
Broadcast Intents – System wide intent that is sent out to all applications that have registered an “interested” Broadcast Receiver.
Service Intents – Same above but in form of background processes.
Activating Components – A unique aspect of Android system design is that any app can start another app’s component through:
o Inter App Activation – This method activates Activities, Services & Broadcast Receivers through Intents. The app must deliver a message to the system that specifies their intent. An app must give its permission for any of its components to be activated by an external intent. When the system starts a component, it starts the process for that app (if it’s not already running) and instantiates the classes needed for the component.
o Content Providers – Activated when targeted by a request from a Content Resolver. The resolver handles all direct transactions with the Content Provider so that the component that’s performing transactions with the provider does not need to, and instead calls methods on the Content Resolver object. Creates a layer of abstraction between the content Provider and component requesting information (for security). More details check week 7 and 8 content.
Example of Activity Intent Coding (Week2App):
1. ActivityIntenttotakeAppintoanotherActivity(ToLowerClass)+sendinga key/value pair of data into that Activity class:
To retrieve our data in ToLower class, we call getIntent() then call intent.getStringExtra(key).
Note: Always initiate the intent using StartActivity() in the end. TextView and EditText
TextView is used to display text that is not editable by the user, by can be updated programmatically at any time.
EditText is used for user input.
Basic functions we will always utilize from TextView and EditText will be .setText()
and .getText().
Layout ID’s and string ID’s
We can identify our components firstly in the layout, every component has a unique ID which we can reference, so for example, an EditText component can have id “strLn” which we can then access the user input by referencing that ID below.
Furthermore, to have more consistent variables, we do not define literal values, but instead, use key constants, we define these in res/values/strings.xml. We can then reference these string key values by calling R.id.stringValue.
Example strings.xml file:
Referencing our string values:
Note: Details about what SharedPreferences are is located in Week 3 Content. View Hierarchy of an App
Detailed Notes in Week 4 Content.
App Manifest File – an XML file which details all an Apps component + capabilities.
o Includes a declaration of all components in the App to inform system
o Also identifies any user permissions the app requires e.g. read-access to
something
o Declares the minimum API level required by the App.
o Declares hardware/software features used or required by the app e.g. camera o Declares API libraries the app needs to be linked against, e.g. Google Maps
library.
Application Resources
An Android application will contain a collection of resource files such as strings, images, fonts, color etc. These are all defined and stored under the res directory of the application. All the resource files (drawable, string, layout, styles etc.) in our app will be contain a resource ID which we can reference and access by calling R in Java, and by @resource in XML.
Using app resources makes it easy to update characteristics of our app without modifying code and – by providing sets of alternative resources, enables us to optimize our app for a variety of device configurations (e.g. screen size, language, orientation etc.)
Referencing in Java
R.layout.*, R.string.*, R.id.*, R.style.*, R.color.*, R.drawable.*. Referencing in XML
@+id/.*/, @color/.*/, @layout/.*/, @style/.*/, @drawable/.*/. Application Context
Context is an Interface to global information about an application environment. It is an abstract class whose implementation is provided by Android. It allows access to application-specific resources and classes. In our class, we reference this by ‘this’.
When an app is compiled, a class named R is created which contains references to the application resources. The app manifest file and these resources combine to create the Application Context. This Context is used to gain access to application resources at runtime, plus a wide range of methods to gather information.
Bundle, what is it?
In all our App’s onCreate() callback, we see that there is an object of type Bundle. A Bundle is an object storing data as key/value pairs that is passed around Activities in Android to transmit information.
To store information into a Bundle, we store data similarly to how we do it in an Intent.
Instead of intent.putExtra(key, value) we call outState.putString(key, value) assuming our Bundle object is called “outState”.
Then to retrieve our key/value, we call instate.getString(key).
We will see in Week 3 that Bundle is used to save/restore our app’s view state and is used in 3 important callback methods: onCreate(), onSaveInstanceState(), onRestoreInstanceState().
Week 3: Android Activity Lifecycles, Instance State, Persistent Data, Intents
Activities have 4 possible Lifecycle states which transition as a result of user interaction and OS process kills.
1. Foreground
2. Partiallyhidden 3. Fullyhidden
4. Destroyed
The Activity class provides several callback’s that allow the activity to know that a state has changed: that the system is creating, stopping, resuming, or destroying an activity.
Different events, some user-
triggered, and some system-
triggered, can cause an
Activity to transition from one state to another.
Lifecycle Callback’s – Within the lifecycle callback methods, we can declare how our activity behaves when the user leaves and re-enters the activity by:
• Overriding all Lifecycle callbacks to perform customised processing required of our app (make sure to call the super method! – super performs a lot of default standard processing required).
• e.g. onCreate() override begins with super.onCreate()
• onSaveInstanceState() & onRestoreInstanceState() are important Activity
callback methods that plays a role in saving the view state of an Activity.
Types of Data in an Activity Instance State
Note: Not to be confused with Activity’s Lifecycle State Data can consist of:
1. Activity view data – the state of all Views in the Activity’s layout
2. Activitynon-viewdata–Activityinstancevariables
3. Persistentdata–dataassociatedwithmultipleusesoftheActivityseparatedby
any amount of time i.e. it spans an Activity’s instances
Initial Case: Launching App for First Time
Every time an App Launches, it will always go through the initial lifecycle callback’s:
1. onCreate() 2. onStart()
3. onResume()
There is nothing to restore, (remember that the restore callback only gets called if the bundle is not null, hence no need to call onRestoreInstanceState callback.
Common Case 1: Configuration change occurs – Many occurrences, such as device reorientation, input device, language changes.
For a configuration change, the Activity is destroyed and recreated. Android also automatically preserves the UI state during configuration change through:
1. onSaveInstanceState(Bundle outState) – Method saves the View-state from an activity before being killed so that the state can be restored in onRestoreInstanceState(Bundle inState).
Note: savedInstanceState is a reference to a Bundle object that is passed into the onCreate() method of every Android Activities.
Activities can restore themselves to a previous state using the data stored in this bundle; if there is no instance data, then savedInstanceState defaults to null.
Note: onRestoreInstanceState(Bundle inState) only gets executed if inState != null.
Note: We define our own implementation of this method if we want to save additional non-view data. We still call the superclass default implementation as we want it to save the state of the view data.
2. onRestoreInstanceState(Bundle inState) – called after onStart() when the activity is being re-initialized, data to restore is given in inState.
Same thing applies above, we create our own implementation of the method to restore non-view data, but still call default super method to restore view data.
So, the activity callback lifecycle for a configuration change will go like this:
1. onPause()
2. onSaveInstanceState(Bundle outState) – outState is the saved state to be
placed into the Bundle object
3. onStop()
4. onDestroy()
5. onCreate()
6. onStart()
7. onRestoreInstanceState(BundlesavedInstanceState)–savedInstanceStateis
the data most recently supplied in onSaveInstanceState(Bundle).
Only called when data in Bundle is not null.
8. onResume()
Common Case 2: User taps Back button – Tapping the Back button indicates to Android that the user is done with the Activity and so it will not save the view-state (not call onSaveInstanceState). Hence the Activity is destroyed and is also removed from the back stack.
To navigate back, we have to relaunch the activity, with nothing to restore as the state is lost.
So, the activity callback lifecycle will go like: 1. onPause()
2. onStop()
3. onDestroy()
Note: We could still code to restore our view-state by having a sharedPreferences file for saving and restoring data. We can call saveSharedPreferences() during onPause() and restoreSharedPreferences() during onStart().
This allows us to still save our data despite user tapping “back” button. SharedPreferences?
SharedPreferences Object files are Objects which points to a non-volatile (permanent) memory file (we can specify filename if needed) and stores data sets as key/value pairs. They are useful for storing small-scale information where it is unnecessary to use a database to implement.
Example Implementation See Below
Common Case 3: Activity or dialog appears in foreground Partial Hide
If a new activity or dialog appears in the foreground, and partially covers the activity, the covered activity enters the paused state by calling onPause(). When the covered activity returns to the foreground and regains control, it calls onResume().
So, in this case, the Activity is NOT destroyed, and the instance state remains intact.
So, the activity callback lifecycle on a partial hide will go like: 1. onPause()
2. onResume() Full Hide
Another case is if the Activity gets fully covered from another Activity, in this case, the Activity is restarted, and Android automatically saves the view-state, we can also manually code to also save our non-view state in the same Bundle.
So, the activity callback lifecycle on a full hide will go like:
1. onPause()
2. onSaveInstanceState()
3. onStop()
4. onRestart()
5. onStart()
6. onRestoreInstanceState() 7. onResume()
Back Stacks – A collection of inter-connected activities that users interact with.
The activities are arranged in a stack in order of activity opened. When user presses Back button, current activity is popped from the stack (destroyed), and previous activity resumes (onPause to onResume). Continually pressing back will eventually pop the stack until it reaches the Home screen.
Note: A back stack can include Activities from several different apps (remember an Activity can Intent an Activity in another App). There can also be multiple background back stacks.
Summary of Types of Lifecycle Events
1. Activity is partially or fully hidden
a. For partial hide, Activity is still in memory, no state data (view or non-view)
is lost.
b. For full hide, Activity gets restarted but Android automatically saves the
Activity’s view state away in a Bundle object.
c. Persistent data remains in its last updated state in non-volatile memory
2. Configurationeventssuchasreorientation
a. This is interpreted by Android as still requiring the activity view-state,
however the Activity must be destroyed for reorientation, so it saves it in a Bundle object which it uses on relaunch to restore the Activity’s view- state.
b. Lifecycle callback is a bit similar to a full hide action, in this one, the Activity is destroyed, in a full hide, the Activity is restarted.
3. Activity is destroyed by back button or user swipes activity from recent/overview
a. Android interprets as view-state no longer required so does not save it
b. Persistent data remains in its last updated state in non-volatile memory
c. Android does not even call onSaveInstanceState so there will be no view-
state saved.
Note: Developers must code manually to save and restore non-view data in the same Bundle Object. This is done by overriding the onSaveInstanceState() and onRestoreInstanceState() methods and inserting key/value pairs into the Bundle.
Note: When an app is uninstalled from the device, all its data including persistent data stored in non-volatile memory is lost
Note: Make sure to call super on all overridden lifecycle callback methods. E.g. super.onSaveInstanceState(outState), super.onStop(), super.onStart() etc.
Example Code for Saving/Restoring an Activity Instance State (view + non-view)
1. onSaveInstanceState(BundleoutState)
a. Not called if user indicates they are done with the activity (Back)
b. Must call super to let Android save view-state
c. Must code to manually save non-view state in Bundle (such as instance
variables).
Below is the week’s example:
1. FirstsetavalueinanEditTextinputboxthroughabutton.
2. putthevariabledataintotheBundleasakey/valuepairbycallingputString()on
onSaveInstanceState(Bundle outState)
3. RetrievethevariabledatabackbycallingthekeyintheBundleon
onRestoreInstanceState(Bundle inState)
Saving/Restoring Persistent Activity Data (data across all an app’s uses that is not likely to be modified)
Many options… (All writes to and reads from the device’s non-volatile memory):
1. SavingKey-Valuesets
2. Savingfiles
3. SavingDatainSQLDatabases(Week7+)
Saving/Restoring Persistent Activity Data through Key/Value Sets
• Works by using a shared preferences file for storing small data. We use an Editor object to create/edit key-value sets, then we call commit() or apply() the changes to the file system.
• We restore our persistent values from a SharedPreferences file as variables in onCreate, if there is nothing to restore then set default values.
• We update these variables holding current persistent values as required during activity operation
• We save the values of these variables holding current persistent values to their SharedPreferences file in onPause.
• we save our variables by calling editor.putString(key, value) and retrieve by calling sp.getString(key, default_value)
Below is the week’s example:
1. First get the data by creating a variable to take the EditText input string
2. ThenwecreateafunctionwhichsetsthePersistentState/Databycreatinga SharedPreference file and Editor, storing as key/value pair, and calling commit()
Note: If we want to save data in a specific filename then we can specify by:
3. Finally, we create a function to restore the data back into our EditText input.
4. Most importantly, we call our functions during the lifecycle of our app at onPause and onStart to save the data during Activity lifecycle changes.
During onPause(), the persistent data is stored as a key-value pair in the shared Preferences file.
During onStart(), the persistent data is restored from the shared Preference file, or if null, then default value is empty string.
Note: What is the difference between SharedPreferences and Bundle?
SP is an Object which points to a non-volatile memory file (we can specify filename if needed) and stores data sets as key/value pairs. Useful for retaining data between different app executions. Bundle is used to safely transfer data between activities or fragments and stores volatile data.
Similarities: They both store data as key/value pairs.
Similarities: Both have similar functions to store/retrieve key values:
SP: store is editor.putString(key, value). Retrieve is sp.getString(key, default_value).
Bundle: store is outState.putString(key, value). Retrieve is inState.getString(key).
Note: Difference between getSharedPreferences() and getPreferences()?
getSharedPreferences() is used when we need multiple SharedPreference files identified by name, so we specify two parameters, the filename, and the mode.
getPreferences is used when we only need one SharedPreference file for the activity (hence do not need to specify filename), so we specify one parameter only, the mode.
We only use mode 0, which means the SharedPreference data can only be accessed by that specific activity.
Week 4: Simple UIs & Layouts (Constraint layout, XML, Screen Size & Resolution, Views, ViewGroups)
Views, ViewGroups, Layouts, Layout.Params
A Layout defines the structure of our UI in our app, with all elements built using a
hierarchy of View and ViewGroup objects.
View class – imported from the package android.view.View
Represents the basic building block for UI components. A View occupies the area on screen responsible for drawing and event handling. Is the base class for widgets, which are used to create interactive UI components (buttons, text fields etc).
ViewGroup subclass – imported from package android.view.ViewGroup
The base class for Layouts and Views containers, it is a special View that contains other View’s as its children. A ViewGroup allows View’s to be nested, which is represented as a hierarchy called a Layout.
A Layout is responsible for managing the size, position and behaviour of all the Views it contains.
An example of a ViewGroup is LinearLayout or RelativeLayout, which are both subclasses of ViewGroup.
ViewGroup.LayoutParams – Sets of XML attributes used by the parent ViewGroup to define the size and position for each child View.
Every Layout Class contains:
1. XML attributes (also inherit attributes from View and ViewGroup)
2. Java methods which applies directly to the View’s Layout Params object e.g.
addView(View child)
Layout Types
ViewGroup has several Layout subclasses such as:
CoordinatorLayout, FrameLayout, GridLayout, LinearLayout, RelativeLayout
and indirect subclasses such as TableLayout.
Note: since a ViewGroup is a View, a ViewGroup can be contained by another ViewGroup.
So, Layouts can be nested to optimise parts of the UI, however, nesting can create efficiency and clarity issues, which is why Google introduced ConstraintLayout (see later).
In Addition to ViewGroups
There is something called a View container, which contains many direct and indirect container subclasses that can be part of a UI’s View hierarchy (e.g. Toolbar).
Layout Parameters
XML layout attributes defining layout parameters for the View that are appropriate for the ViewGroup in which it resides.
Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams – this subclass contains properties that define the size and position for each child view, as appropriate for the view group.
The parent ViewGroup defines the layout parameters for each child View.
There are many Layout Attributes that the class supports such as width, height, margin, etc. Base LayoutParams class just describes how big the view wants to be for both width and height. It can specify one of:
match_parent = view should be as big as its parent ViewGroup will allow wrap_content = view should be only big enough to enclose its contents
Creating UIs in XML and Java
We can declare a layout in two ways:
1. Declare UI elements in XML, seen above.
2. Instantiate layout elements at runtime. Android creates View and
ViewGroup objects (and are able manipulate their properties) programmatically.
Android Studio IDE allows us to use either or both these methods. Java VS XML for UI Design
XML is better for separations of concerns – can separate the presentation of App from the behaviour of App.
Using XML files also makes it easy to provide different layouts for different screen sizes and orientations (easy resource selection).
Generally, XML vocabulary for UI elements closely follows the structure and naming of the classes and methods.
1. View Properties are often straightforward
a. XML: widget attribute: android:text = “ “; b. Java: widget method: .setText(…);
2. View Layout parameters are more complicated in code e.g.
a. XML:widgetattribute:android:layout_centerHorizontal=”true” b. Java: .addRule(RelativeLayout.CENTER_HORIZONTAL)
Example code defining UI elements through XML
Defining UI elements in Java
Basic Procedure is…for each widget:
1. Instantiatethewidgetandcustomiseitbysettingitspropertiesusuallyusing “setPropName” methods.
2. InstantiatetheLayoutobjecttoplacewidgeton 3. Instantiate a LayoutParams object for the widget
a. typedependsonthelayout(e.g.RelativeLayout.LayoutParams)
b. Use constructor and addRule method to specify the size, position and
behaviour of the widget in the layout
c. Add the widget to the layout using addView() method with 1st
parameter being the widget, and 2nd parameter being the LayoutParams object
Example Code defining UI elements (button in this case) through Java
View Properties
Every View API has a class reference page in Android Doco’s e.g. TextView Contains a table of XML attributes and a table of Java methods
Example TextView XML attributes Example Java Methods for TextView
ViewGroup Layout for Week 4
For Week 4 Calculator App, we use TableLayout, which is a subclass of
LinearLayout, and consists of a number of TableRow objects.
TableRow objects are by itself, layouts which arrange its child View’s horizontally.
TableLayout is a layout that arranges its children into rows (through TableRow) and columns. Each row has zero or more cells, and each cell can hold one View object. the # of columns is dictated by the row with the most cells (Views).
ConstraintLayout – Proposed solution to nested layouts, views are all linearly placed
Available to API level 9 with Android 2.3 and higher.
o Views are attached to the layout through software analogues of springs or through horizontal and vertical guidelines
o These springs can expand and collapse
o Tension on springs holding a View between two endpoints can be biased towards
one end by a percentage
o Hard margins can be specified at the end point of each spring
ConstraintLayout.LayoutParams
As stated, every ViewGroup implements a nested class that extends ViewGroup.LayoutParams. in this case it is ViewGroup.LayoutParams, Important attributes are:
match_constraint – layout size is defined by the size of the constraint hence is always 0dp.
Example: a View’s width and height both constrained under “match_constraint”. Meaning size of the view matches the constraint, hence is 0dp. Vertical and horizontal bias are redundant.
wrap_content – size is defined by the required caption size of the view
Example: Similar to above except constrained under “wrap_content”. Vertical and horizontal bias are considered, and hence positioned slightly upwards in height, and leftwards in width.
specific dimension values – specify the absolute values in size of the view – NOT RECOMMENDED DUE TO DEVICE VARIATION
Example: Similar to above, vertical and horizontal bias are considered.
Guidelines and Barriers
Other than software analogues of springs, we can also structure our View’s by creating transparent horizontal/vertical guidelines or barriers to constrain (nest) our views onto.
The Difference between a Barrier and a Guideline is that a Guideline defines its own position, whereas a Barrier does NOT define its own position. A Barrier’s position is fixed based on the largest absolute position of the views nested within it.
Essentially, A Barrier’s position is flexible and always based on the size of the largest views that it references. A Barrier specifies the most extreme size of its views on the specified side whereas a Guideline’s position is always fixed.
Chains
Another way to structure our View’s is through chaining. We can chain multiple View’s into a linked bi-directional position constraint. There are 3 main styles of chaining by specifying the attribute:
Spread: views are evenly distributed Packed: views are packed together
Spread inside: first and last view are affixed to the constraints on each end of the chain but rest are evenly distributed.
Additional Notes
Example ConstraintLayout Code
We have a ConstraintLayout ViewGroup which nests all our Views, with a Barrier which references 4 TextView’s. There are also 4 EditText’s and 3 Buttons.
o 7 Horizontal guidelines created to structure layout, with position specified by vertical percentage values.
o 4 EditText Objects are constrained under their respective guideline.
o Barrier defined and 4 TextView objects are nested under it. Barrier size is defined by the maximum width of its TextViews (longest text).
o TextView size is constrained under size of EditText Views on the right.
o Horizontal constraint defined for the lower buttons through chains with “spread” attribute.
o Vertical constraint is placed on buttons through its respective guideline
Styles, Themes and Material Design
Style – A collection of attributes that specify the look and format for a View or window. A style is defined in an XML resource that is separate from the layout XML
file, located under values/styles.xml.
Style Inheritance – parent attribute in the