0% found this document useful (0 votes)
44 views93 pages

Android Basic UI-2019

Uploaded by

shoab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views93 pages

Android Basic UI-2019

Uploaded by

shoab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Mobile Application Development

User Interface Basics


The View Class
• 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.
– Examples: buttons and text
fields
• A ViewGroup is an object that
holds other View (and
ViewGroup) objects in order to
define the layout of the
interface.
– Examples: linear or relative
layout
Graphical UI to XML Layout
UI Via XML
• Each Screen in your app will likely have an xml layout file
describes the container and widgets on the screen / UI
• Edit XML file or use drag and drop editor
• Alter container and layout attributes for the set up you
want
• We can access and manipulate the container and
widgets in our Java code associated with the UI / screen.
Using Views
Dealing with widgets & layouts typically involves the following
operations:
1. Set properties: For example setting the background color,
text, font and size of a TextView.
2. Set up listeners: For example, an image could be
programmed to respond to various events such as: click,
long-tap, mouse-over, etc.
3. Set focus: To set focus on a specific view, you call the method
requestFocus() or use XML tag <requestFocus />
4. Set visibility: You can hide or show views using
setVisibility(...).
Common Layouts
Linear Layout: Horizontal

File: res/layout/activity_main1.xml
Linear Layout: Horizontal

res/layout/activity_main2.xml
Relative Layout
In android, RelativeLayout is a ViewGroup which is used to specify the position
of child View instances relative to each other (Child A to the left of Child B) or
relative to the parent (Aligned to the top of parent).

res/layout/activity_main2.xml
Relative Layout
Attributes to control the relative position of views within a Relative Layout.
UI Programming with Widgets
• Widgets are an element in a Graphical User Interface
(GUI)
– not to be confused with app widgets placed on the home
screen, mini version of app
• Widgets are building blocks
• User interacts with a given widget
• Often use prebuilt widgets
– Advanced developers create their own (Chris Renke,
Square)
Widgets
• Including:
• Text Views
• Buttons
• Check Boxes
• Spinners (drop down
menus)
• and many, many more
Common Widgets for Input
Control
Widget Attributes
• Size
– layout width
– layout height
• Margin
• Padding

No specified margin Top Margin of 30dp Top Margin of 30dp,


or padding (density independent pixels) padding of 20dp
Size
Three options:
• Specified (hard coded) size in dp, density
independent pixels
• wrap_content
– widget is just big enough to show content
inside the widget (text, icon)
• match_parent
– match my parent's size
– widgets stored in a container or ViewGroup
Size - Wrap Content
Size - Match Parent
Attributes
a lot of attributes

attributes can be set in the xml and most can changed


programmatically
in layout xml file

Programmatically in Activity (Java code)

in program
Dimension of Widgets
A dimension value defined in XML. A dimension is specified with a number
followed by a unit of measure. For example: 10px, 2in, 5sp.

The following units of measure are supported by Android:


• dp : density-independent pixels
• sp : scale-independent pixels
• pt : points – 1/72 of an inch
• px : Actual pixels; advice not to use.
• mm : millimeters
• in : inches
Dimensions: dp
Density-independent Pixels

An abstract unit that is based on the physical density of the


screen. These units are relative to a 160 dpi (dots per inch)
screen, on which 1dp is roughly equal to 1px.

When running on a higher density screen, the number of


pixels used to draw 1dp is scaled up by a factor appropriate
for the screen's dpi. Likewise, when on a lower density
screen, the number of pixels used for 1dp is scaled down.

Using dp units (instead of px units) is a simple solution to


making the view dimensions in your layout resize properly for
different screen densities. In other words, it provides
consistency for the real-world sizes of your UI elements
across different devices.
Dimensions: sp
Scale-independent Pixels

This is like the dp unit, but it is also scaled by the user's font
size preference. It is recommend you use this unit when
specifying font sizes, so they will be adjusted for both the
screen density and the user's preference.
Dimensions: pt
Points

1/72 of an inch based on the physical size of the screen, assuming a


72dpi density screen.
Dimensions: px
Pixels

Corresponds to actual pixels on the screen. This unit of measure is


not recommended because the actual representation can vary across
devices; each devices may have a different number of pixels per inch
and may have more or fewer total pixels available on the screen.
Dimensions: mm, in
mm : Millimeters - Based on the physical size of the screen.

In : Inches - Based on the physical size of the screen.


TYPES OF WIDGETS
Common Controls - TextView
• a simple label
• display information, not for interaction
• common attributes: width, height, padding,
visibility, text size, text color, background color
– units for width / height: px (pixels), dp or dip
(density-independent pixels 160 dpi base), sp
(scaled pixels based on preferred font size), in
(inches), mm (millimeters)
– recommended units: sp for font sizes and dp for
everything else
– http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
Common Controls - Button
• Text or icon or both on View
• button press triggers some action
– set android:onClick attribute in XML file
– OR create a ClickListener object, override onClick
method, and register it with the checkbox
• typically done with
anonymous inner class
– possible to customize
appearance of buttons
http://developer.android.com/guide/topics/ui/
controls/button.html#CustomBackground
Common Controls - EditText
• Common component
to get information from
the user
• long press brings up
context menu
EditText
• can span multiple lines via android:lines
attribute
• Text fields can have different input
types, such as number, date, password,
or email address
– android:inputType attribute
– affects what type of keyboard pops up for
user and behaviors such as is every word
capitalized
Auto Complete Options
• Depending on EditText inputType suggestions
can be displayed
– works on actual devices

• Developer list
– use ArrayAdapter connected to array
– best practice: put array in array.xml file
AutoComplete Using Array
Spinner Controls
• Similar to auto
complete, but user
must select from a set
of choices
Spinner Control

strings.xml in res/values
Simple User Selections
• CheckBox
– set
android:onClick attribute or create a
ClickListener object, override
onClick method, and register it with
the checkbox
• Switches and ToggleButton
– similar to CheckBox with two states,
but visually shows states
– on and off text
RadioButton
• Select one option
from a set
• set onClick method for
each button
– generally same method
• Collected in RadioGroup
– sub class of LinearLayout
– vertical or horizontal
orientation
Pickers
• TimePicker and DatePicker
• Typically displayed in a TimePickerDialog
or DatePickerDialog
– dialogs are small windows that appear in
front of the current activity
Indicators
• Variety of built in indicators in addition to
TextView
• ProgressBar

• RatingBar

• DigitalClock
• AnalogClock
SeekBar
• a slider
• Subclass of progress bar
• implement a
SeekBar.OnSeekBarChangeListener to
respond to changes in setting
INTERACTING WITH WIDGETS
Interacting with Widgets
• Some widgets simply display information.
– TextView, ImageView
• Many widgets respond to the user.
• We must implement code to respond to
the user action.
• Typically we implement a listener and
connect to the widget in code.
– logic / response in the code
Example - Display Random Image
• App to display crests TextView
of British Premier
League Football Spinner
teams
• Allow user to select ImageView
team from spinner
control Button

• Or, press button to


display a random
crest
Button in XML layout file

• Notice button reacts when pressed, but


nothing happens
• Possible to disable button so it does not
react
Responding to Button Press
• Two ways:
• Hard way, create a listener and attach to
the button
– shorter way exists for Views, but this
approach is typical for many, many other
widgets behaviors besides clicking
• Implement an onClickListener and attach
to button
Accessing Button in Code
• R.java file automatically generated and
creates ids for resources in project folder
– if id attribute declared
Setting Activity Layout / GUI
• Usually the GUI for an Activity is set in
the onCreate method.
• Typically a layout file is used

• set content view will inflate runtime


objects for all the widgets in the layout
file
Accessing Layout Widget
• To attach a listener we need a handle (reference) to
the runtime object for the button (or desired widget)

findViewById returns a View object


often necessary to cast to correct type
Creating and attaching a Listener

• setOnClickerListener is method that


attaches the listener
• View.onClickListener is a Java interface
with one method onClick
• We are implementing interface with an
anonymous inner class
onClick Logic
CONTAINERS FOR WIDGETS
VIEW GROUPS
ViewGroups - Layouts
• Layouts are subclasses of ViewGroup
• Still a view but doesn't actually draw
anything
• serves as a container for other views
– similar to Java layout managers
• options on how sub views (and view groups)
are arranged
• Useful Layouts: FrameLayout, LinearLayout,
TableLayout, GridLayout, RelativeLayout,
ListView, GridView, ScrollView,
DrawerLayout, ViewPager
FrameLayout
• FrameLayout
– simplest type of layout object
– fill with a single object (such as a picture)
that can be switched in and out
– child elements pinned to top left corner of
screen and cannot be move
– adding a new element / child draws over
the last one
LinearLayout
• Supports a filling strategy in
which new elements are
stacked either in a horizontal
or vertical fashion.
• If the layout has a vertical
orientation new rows are
placed one on top of the other.
• A horizontal layout uses a side-
by-side column placement
policy.
LinearLayout Attributes
Configuring a LinearLayout usually requires
you to set the following attributes:
LinearLayout - Orientation
LinearLayout - Fill Model
• Widgets have a "natural size“
based on their included text
(rubber band effect).
• On occasions you may want your
widget to have a specific space
allocation (height, width) even if
no text is initially provided (as is
the case of the empty text box
shown below).
LinearLayout - Fill Model
All widgets inside a LinearLayout must include ‘width’ and ‘height’ attributes.
android:layout_width
android:layout_height
Values used in defining height and width can be:
1. A specific dimension such as 125dp (device independent pixels, a.k.a. dip
)
2. wrap_content indicates the widget should just fill up its natural space.
3. match_parent (previously called fill_parent) indicates the widget wants
to be as big as the enclosing parent.
LinearLayout - Fill Model
LinearLayout - Layout Weight
android:layout_weight
indicates how much of the
extra space in the
LinearLayout will be
allocated to the view. The
bigger the weight the
larger the extra space given
to that widget.

Use 0 if the view should not be


stretched.
LinearLayout Layout Gravity
- Indicates how a control will align on the
screen.
- By default, widgets are left- and top-
aligned.
- Use android:layout_gravity="..." to set
other arrangements: left, center, right,
top, bottom, etc.
gravity vs. layout_gravity
• android:gravity sets
the gravity of the content of
the View it's used on
• android:layout_gra
vity sets the gravity of
the View or Layout in its
parent
Margin and Padding
Margins are the spaces outside the border, between the border
and the other elements next to this view.
Controlled by android:layout_margin property.

Padding is the space inside the border, between the border and
the actual view's content.
Controlled by android:padding property.
Margin
Padding
Margin and Padding
RelativeLayout

The placement of widgets in a


RelativeLayout is based on their
positional relationship to other widgets
in the container and the parent
container.
RelativeLayout
RelativeLayout - Referring to
the container
Below there is a list of some positioning XML boolean properties (=“true/false”) useful for collocating a widget based on the
location of its parent container.
TableLayout
• rows and columns
• rows normally
TableRows (subclass
of LinearLayout)
• TableRows contain
other elements such
as buttons, text, etc.
GridLayout
• added in Android 4.0
• child views / controls can span multiple
rows and columns
– different than TableLayout
• child views specify row and column they
are in or what rows and columns they
span
A Toast
"A toast provides simple
feedback about an
operation in a small
popup."
Creating a Toast
• Inside the OnItemClickListener
anonymous inner class
Other Layouts - Tabbed Layouts
• Uses a TabHost and
TabWidget
• TabHost consists of TabSpecs
• can use a TabActivity to
simplify some operations
• Tabs can be
– predefined View
– Activity launched via Intent
– generated View from
TabContentFactory
Scrolling
• ListView supports vertical scrolling
• Other views for Scrolling:
– ScrollView for vertical scrolling
– HorizontalScrollView
• Only one child View
– but could have children of its own
• examples:
– scroll through large image
– Linear Layout with lots of elements
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.
• Not recommended
Constraint Layout
• Position and size widgets in a flexible way
• Constraints available:
– Relative positioning
– Centering positioning
– Circular positioning
– Chains of widgets
Attaching Layouts to Java Code
CONCRETE UI EXAMPLE -
TIP CALCULATOR
Concrete Example
• Tip Calculator
• What kind of layout
to use?
• Widgets:
– TextView
– EditText
– SeekBar
TextViews
EditText

All but top


EditText are
uneditable

Alternative?
TextViews?
SeekBar
Layout
• TableLayout

row 0
row 1
row 2

row 3
row 4
row 5
Color Resources

• Good Resource / W3C colors


– http://tinyurl.com/6py9huk
StretchColumns

• columns 0 indexed
• columns 1, 2, 3 stretch to fill layout width
• column 0 wide as widest element, plus
any padding for that element
Initial UI
• Done via some Drag
and Drop, Outline
view, and editing
XML
• Demo outline view
– properties
Changes to UI
• change bill total and
seekbar to span more
columns
• gravity and padding for text
in column 0
• align text with seekBar
• set seekBar progress to 18
• set seekBar focusable to
false - keep keyboard on
screen
Changes to UI
• Prevent Editing in
EditText
– focusable, long clickable,
and cursor visible
properties to false
• Set text in EditText to
0.00

You might also like