L02 - Android Layout (ITP4501) 2020

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

Android Layouts

Android Layouts 1
Android - Fragmentation

Android devices come in all shapes and sizes,


with vastly different performance levels and
screen sizes - fragmentation problem.

http://opensignal.com/reports/fragmentation-2013/
Android Layouts 2
Android UI Design Challenges

To fit a wide range of screen size and resolution


is one of the big challenges an Android
developer has to face.

Android Layouts 3
Flexible UI Design

One solution is to use flexible layout


management.
Instead of specifying where the UI components
are places, you declare how the UI objects are
organised in a container.
When your application runs on a device, the
container will calculate the location and
dimension of each UI object.
This is a proven method – already works well in
web and windows applications.

Android Layouts 4
Android User Interface

Your app's user interface is everything that the


user can see and interact with.
Android provides a variety of pre-build UI
components such as structured layout objects
and UI.

Android Layouts 5
Android User Interface

All user interface elements in an Android app


are built using View and ViewGroup objects.
A View is an object that draws something on
the screen that the user can interact with.
The View class represents the basic building
block for user interface components. A View
occupies a rectangular area on the screen.
View is the base class for widgets, which are
used to create interactive UI components
(buttons, text fields, etc.).

Android Layouts 6
User Interface

The ViewGroup subclass is the base class for


layouts, which are invisible containers that hold
other Views (or other ViewGroups) and define
their layout properties.
The user interface for each component of your
app is defined using a hierarchy of View and
ViewGroup objects.

Android Layouts 7
View Hierarchy

The hierarchy tree can be as simple or complex


as you need it to be, and you can build it up
using predefined widgets and layouts, or with
custom Views that you create yourself.
Can be a
TableLayout

Can be a
TextView
(Label) object Can be a Button
widget
Picture Source - https://stackoverflow.com/tags/android-layout/info Android Layouts 8
Layout
 You can build android UI in two ways:
• Declare UI elements in XML format
Android provides a set of XML tag, that
allows you to define application's default
layouts in XML, including the screen
elements that will appear in them and their
properties.
• Instantiate layout elements at runtime Your
application can create View and ViewGroup
objects (and manipulate their properties)
programmatically.
Android Layouts 9
XML-based Layout

Advantages for XML-based Layout:


• The advantage to declaring your UI in XML is
that it enables you to better separate the
presentation of your application from the code
that controls its behavior.
• Additionally, declaring the layout in XML
makes it easier to visualize the structure of
your UI, so it's easier to debug problems.
• A common approach for modern GUI
programming including iOS, Windows Phone,
ASP.NET, JSF etc.
Android Layouts 10
XML-based Layout
Each layout file must contain exactly one root
element, which must be a View or ViewGroup
object.
You can add additional layout objects or widgets
as child elements inside a View hierarchy. For
example, the next slide is an XML layout that
uses a vertical LinearLayout to hold a TextView
and a Button.
After declared a layout in XML, save the file
with the .xml extension, in your Android
project's res/layout/ directory, so it will properly
compile.

Android Layouts 11
XML-based Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
Sample
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width=“match_parent"
android:layout_height=“match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />

</LinearLayout> Android Layouts 12


Load the XML resource
The layout resource can be loaded from the
application code, in the Activity.onCreate()
callback implementation.
Do so by calling setContentView(), passing it
the reference to your layout resource in the form
of: R.layout.layout_file_name.
For example:

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Android Layouts 13
Attributes
The attributes of the XML elements are
properties, describing how a widget should
look or how a container should behave.
ID - Any View object may have an integer ID
associated with it, to uniquely identify the
View within the tree.
Example:
◦ A button is defined in the layout file and assigned a
unique ID.
android:id="@+id/my_button"

◦ Then an instance of the view object can be created


and referenced from the application.
Button myButton = (Button) findViewById(R.id.my_button);

Android Layouts 14
Attributes
Layout Parameters - the XML layout
attributes named layout_something contains
property types that define the size and
position for each child view, as appropriate
for the view group.

The parent view group defines layout parameters for each child
view (including the child view group).
https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/ui/declaring-layout.html
Android Layouts 15
Common Layouts

FrameLayout is the simplest layout


LinearLayout likes a box model
RelativeLayout likes a rule-based model
TableLayout likes a grid model
ScrollView
Other, such as ListView, GridView, WebView,
MapView …

Android Layouts 16
FrameLayout
FrameLayout is an area on the screen to display
a single item.
You can add multiple children to a
FrameLayout, but all children are pinned to the
top left corner of the screen. You cannot specify
a different location for a child view.
Adding multiple views to a frame layout just
stacks one on top of the other (overlapping the
views).

Android Layouts 17
LinearLayout

LinearLayout is a box model – widgets or


child containers are lined up in vertical or
horizontal direction.

Android Layouts 18
LinearLayout

Properties of LinearLayour container:


◦ Orientation
◦ Fill model
◦ Weight
◦ Gravity
◦ Padding
◦ Margin

Android Layouts 19
Orientation in LinearLayout

To Indicate whether the item(s) presents in a row


(HORIZONTAL) or a column (VERTICAL).
The orientation can be modified at runtime by
invoking setOrientation().
Horizontal

Vertical

Android Layouts 20
Orientation in LinearLayout
 Or, add the android:orientation property to your
LinearLayout element in your XML layout, setting
the value to be horizontal / vertical.
<LinearLayout
android:id="@+id/myLinearLayout"
android:layout_width=“match_parent"
android:layout_height="match_parent"
android:background="#ff0033cc"
android:padding="4dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" >
<TextView …></TextView>
<EditText …></EditText>
<Button …></Button>
</LinearLayout>
Android Layouts 21
Fill Model in LinearLayout
Widgetshave a "natural" size based on their
accompanying text.
Natural sizes
Empty screen space

Android Layouts 22
Fill Model in LinearLayout

We must address empty screen space in


LinearLayout, therefore all widgets inside a
LinearLayout must supply dimensional
attributes:
◦ android:layout_width
◦ android:layout_height

Android Layouts 23
Fill Model in LinearLayout

Values in defining height and width are:


◦ Specific a particular dimension, such as 125dip
(device independent pixels)
◦ Provide wrap_content, which means the widget
should fill up its natural space, unless that is too big,
in which case Android can use word-wrap as needed
to make it fit.
◦ Provide match_parent, which means the widget
should fill up all available space in its enclosing
container, after all other widgets are taken care of.

Android Layouts 24
Fill Model in LinearLayout
325dip
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout …
125dip
android:orientation="vertical"

>
<TextView android:id="@+id/labelUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
… ></TextView>
<EditText android:id="@+id/ediName"
android:layout_width=“match_parent"
android:layout_height="wrap_content"
… ></EditText>
<Button android:id="@+id/btnGo"
android:layout_width="125dip"
android:layout_height="wrap_content"
… ></Button>
</LinearLayout>
Specific size: 125 dip
Android Layouts 25
Weight in LinearLayout

Itis used to proportionally assign space to


widgets in a view.
You can give a value (eg. 1, 2, 3, …) to
android:layout_weight for indicating the
proportion of the free space.
Default value is 0.

Android Layouts 26
Weight in LinearLayout

TextView:
android:layout_weight=“2"

EditText:
android:layout_weight=“3"

Button:
android:layout_weight=“1"

Actual size of EditText = It’s natural size + 3 / ( 2 + 1 + 3 )


* screen free space Android Layouts 27
Gravity in LinearLayout

Itmeans the alignment of the widget.


Default value is left-top alignment.
Possible values are left, center, right, top,
bottom, etc.

android:layout_gravity = “right”

Android Layouts 28
Gravity in LinearLayout

gravity vs layout_gravity
◦ android:gravity - specifies how to place the
content of an object, both on the x-and y-axis,
within the object itself.

◦ android:layout_gravity - positions the view


with respect to its parent (i.e. what the view is
contained in).

Android Layouts 29
Padding in LinearLayout

The padding specifies how much space there is


between the boundaries of the widget's "cell"
and the actual widget contents. It just likes the
margins in a word document.
Two alternatives:
◦ android:padding property
◦ or by calling setPadding() at runtime on the widget's
Java object.

Android Layouts 30
Padding in LinearLayout

View’s Edges Margin Top

Padding Top

View’s content

Padding Bottom

Margin Bottom

Boundaries touching other widgets

Android Layouts 31
Padding in LinearLayout
For example, the following EditTextbox has been
changed to display 30dip of padding all round.

30dip <EditText
android:id="@+id/ediName"
android:layout_width=“match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="30dip"
>
</EditText>
...

Android Layouts 32
Padding in LinearLayout
By default, widgets are tightly packed next to each
other. To increase space between them use the
android:layout_margin attribute.

<EditText
android:id="@+id/ediName"
android:layout_width=“match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
Increased the inter-widget
space android:layout_margin=“6dip“
>
</EditText>
...

Android Layouts 33
AbsoluteLayout

A layout that lets you specify exact locations


(x/y coordinates) of its children.
Absolute layouts are less flexible and harder to
maintain than other types of layouts without
absolute positioning.

Y=98dip
X=76dip

Android Layouts 34
AbsoluteLayout
<?xml version="1.0" encoding="utf-8"?> <EditText
<AbsoluteLayout android:id="@+id/etName"
android:id="@+id/myLinearLayout" android:layout_width=“match_parent"
android:layout_width=“match_parent" android:layout_height="wrap_content"
android:layout_height=“match_parent" android:textSize="18sp"
android:background="#ff0033cc" android:layout_x="0dip"
android:padding="4dip" android:layout_y="38dip“ >
xmlns:android="http:// </EditText>
schemas.android.com/apk/res/android"
> <Button
<TextView android:layout_width="120dip"
android:id="@+id/tvUserName" android:text="Go"
android:layout_width=“match_parent" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:textStyle="bold"
android:background="#ffff0066" android:id="@+id/btnGo"
android:text="User Name" android:layout_x="100dip"
android:textSize="16sp" android:layout_y="170dip" />
android:textStyle="bold"
android:textColor="#ff000000" </AbsoluteLayout>
android:layout_x="0dip"
android:layout_y="10dip“ >
</TextView>

Warning: Avoid using AbsoluteLayout!


Android Layouts 35
Constrain Layout
• ConstraintLayout allows you to create
large and complex layouts with a flat
view hierarchy (no nested view
groups).
• All views are laid out according to
relationships between sibling views
and the parent layout.
• Easy to use with Android Studio's
Layout Editor.
• Constrain Layout Video
https://youtu.be/XamMbnzI5vE
Android Layouts 36
ScrollView

Itprovides a sliding or scrolling access to the


data. This way the user can only see part of your
layout at one time, but the rest is available via
scrolling.

Android Layouts 37
Example of ScrollView
<?xml version="1.0" encoding="utf-8"?> <TextView
<ScrollView android:id="@+id/textView3"
android:id="@+id/myScrollView1" android:layout_width=“match_parent"
android:layout_width=“match_parent" android:layout_height="wrap_content"
android:layout_height=“match_parent" android:background="#ffccffcc"
android:background="#ff009999" android:text="Line3"
> android:textSize="70dip"/>

<LinearLayout <TextView
android:layout_width="match_parent" android:id="@+id/textView4"
android:layout_height="match_parent" … />
android:orientation="vertical" >
<TextView
<TextView android:id="@+id/textView5"
android:id="@+id/textView1" … />
android:layout_width=“match_parent"
android:layout_height="wrap_content" <TextView
android:background="#ffccffcc" android:id="@+id/textView6"
android:text="Line1" … />
android:textSize="70dip"/>
<TextView
<TextView android:id="@+id/textView7"
android:id="@+id/textView2" … />
android:layout_width=“match_parent"
android:layout_height="wrap_content" </LinearLayout>
android:text="Line2" </ScrollView>
android:textSize="70dip"/>
Android Layouts 38
Other example

Android Layouts 39
Devices and Displays

Android Layouts 40
• There are Android devices with a wide variety of
screen sizes and resolutions.
• Be flexible – Stretch and compress your layouts to
accommodate various heights and widths.
• Optimize layouts – On large devices, create compound
views that combine multiple views to reveal more content
and ease navigation.
• Work for all – Handle devices with different screen
densities (DPI) to ensure that the app looks great on any
device.

Android Layouts 41
Supporting multiple screens
• Screen size – Actual physical size, measured in
screen’s diagonal.
• Four generalized sizes: small, normal, large, xlarge.
• Screen density – The quantity of pixels within a
physical area of the screen, usually referred to as
dpi (dots per inch).
• Four generalized densities: low (ldpi), medium (mdpi), high
(hdpi), extra high (xhdpi).

Update: xxhdpi
(~480dpi) is added
in 2013!

Android Layouts 42
Supporting multiple screens
• To optimize user experience on different screen sizes, you
can create a unique layout XML file for each screen size you
want to support.
• Each layout should be saved into the appropriate resources
directory, named with a -<screen_size> suffix.
• For example, a unique layout for large screens should be
saved under res/layout-large/.
MyProject/ The file names must be
res/ exactly the same, but their
layout/ contents are different in order
main.xml to provide an optimized UI for
layout-large/ the corresponding screen
main.xml size.

• The system loads the layout file from the appropriate layout
directory based on screen size of the device on which your
app is running.

Android Layouts 43
Supporting multiple screens
• As another example, here's a project with an alternative
layout for landscape orientation:
MyProject/
res/
By default, the
layout/
layout/main.xml file
main.xml
is used for portrait
layout-land/
orientation.
main.xml

Landscape orientation
Portrait orientation

Android Layouts 44
Create Landscape in Android Studio
• Create the Portrait Layout first (default layout)
• And then under the icon menu bar of Layout,
choose orientation button and then select "Create
Landscape Variant"
• You will find you have got one more layout with
the word "(land)"

Android Layouts 45
Density independence
• Density-Independent Pixel (dp)
• A virtual pixel unit that you should use when defining UI
layout, to express layout dimensions or position in a
density-independent way.
• The dp is equivalent to one physical pixel on a 160 dpi
screen, which is the baseline density assumed for a
“medium” density screen.
• At runtime, Android handles any scaling of the dp units
based on the actual density of the screen in use.
• Conversion: px = dp * (dpi / 160)
• For example, on a 240 dpi screen, 1 dp equals 1.5 physical
pixels.

Android Layouts 46
Density independence
• Maintaining density independence is important
because, without it, a UI element (such as button)
appears physically larger on a low density screen
and smaller on a high density screen.

Without density
independence

With density
independence

Android Layouts 47
How to support multiple screens
• Explicitly declare in the manifest which screen sizes
your application supports.

<supports-screens android:resizeable=["true"| "false"]

android:smallScreens=["true" | "false"]
android:normalScreens=["true" | "false"]
android:largeScreens=["true" | "false"]
android:xlargeScreens=["true" | "false"]
android:anyDensity=["true" | "false"]
android:requiresSmallestWidthDp="integer"
android:compatibleWidthLimitDp="integer"
android:largestWidthLimitDp="integer"/>

Android Layouts 48
• Provide different layouts for different
screen sizes
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-small/my_layout.xml // layout for small screen size
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml / layout for extra large in landscape orientation

res/drawable-mdpi/my_icon.png // bitmap for medium density


res/drawable-hdpi/my_icon.png // bitmap for high density
res/drawable-xhdpi/my_icon.png // bitmap for extra high density

Android Layouts 49
• Provide different bitmap drawables for different
screen densities
• By default, Android scales bitmap drawables (png, gif, jpg)
and 9-Patch drawables (.9.png) so that they render at the
appropriate physical size on each device.
• However, to ensure bitmaps look their best, you should
include alternative versions at different resolutions for
different screen densities.
• res/drawable-hdpi
• res/drawable-mdpi
• res/drawable-ldpi

Android Layouts 50
Support different languages
• To add support for more languages, create
additional values directories inside res/ that
include a hyphen and the ISO country code at the
end of the directory.
• Android loads the appropriate resources according
to the locale settings of the device at run time.
MyProject/
res/
values/
strings.xml
values-fr/
strings.xml

Android Layouts 51
Support different languages
• English (default locale), /values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="title">My Application</string>
<string name="hello_world">Hello World!</string>
</resources>

• French, /values-fr/strings.xml:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="title">Mon Application</string>
<string name="hello_world">Bonjour le monde !</string>
</resources>

Android Layouts 52
Create Multi Language (Locale) in Android Studio

Under the project tree right click on "res" and then select New,
Android Resource Directory.
Choose "Locale" and then click the ">>" button.
Choose the country and corresponding region.

Android Layouts 53
Create Multi Language (Locale) in Android Studio

• However, you cannot find the folder "values-zh-rHK" in your


project tree.
• Change the scope to "Project" and then find the folder
/res/values-zh-rHK.
• Copy the strings.xml to the locale folder and change the
contents.
• If back to "Android" scope, you will find two strings.xml but
one will have (zh-rHK).

Android Layouts 54
Create Multi Language (Locale) in Android Studio

Android Layouts 55
More about Android Studio
• You can apply a three month trial on
the famous online training by using
IVE student email with CNA password.
◦ https://docs.microsoft.com/en-us/visualstu
dio/subscriptions/vs-pluralsight
• And then go to the following tutorial in
pluralsight:
◦ https://app.pluralsight.com/library/courses/
android-start-developing/table-of-contents
• No coding, only on usage of Android
Studio, Layout, and xml files
Android Layouts 56

You might also like