Download 04-ui

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Building User Interfaces and
Basic Applications
Chapter 2
1
Objectives
• Become familiar with Android user interface
• Learn various views and widgets including view
groups
• Implement applications that require various user
interface controls
• Understand adaptive design concepts
• Use adapters to create sophisticated user interfaces
2
GUI Frameworks In General
•
•
•
•
Model-View-Control (MVC) metaphor
Event-based, implicit invocation style
Single thread-ness
Framework classes
• GUI components (views or widgets)
• Layout managers
• Events and event listeners
• Graphics and imaging classes
Q: Example classes in Java AWT/Swing?
*No AWT/Swing included in Android SDK
3
Model-View-Controller
• Android applications tend to rely on the ModelView-Controller design architecture.
Q: Why also separate
• This architecture assigns one of three
roles
that
View from
Control?
objects can play in an application.
View
(UI element)
update UI
notify user action
Control
update data
Model
(data)
notify change
4
UI of Android App
• Defined in XML (e.g., res/layout/activity_main.xml)
• XML vocabulary compiled into corresponding GUI
component classes
• Loaded at runtime in onCreate() method, e.g.,
setContentView(R.layout.activitiy_main)
• Q: Advantages in declaring UI in XML?
• Better separation of concerns (view from control)
• Visualization of UI structure
• Adaptive design (diversity, e.g., screen orientation)
5
GUI Components
• Views, widgets, and view groups
• Composite design pattern (GoF pattern)
• To allow clients to treat both single components and
collections of component identically
• To define recursive data structures such as trees
Client
<<use>>
ImageView
View
*
ViewGroup
6
View vs. ViewGroup
• UI components in android.view and android.widget
• View
•
•
•
•
Has appearance on screen by occupying a rectangular area
Is responsible for drawing and event handling
Is a subclass of a base class android.view.View
Examples: Button, TextView, EditText, ImageView, etc.
• ViewGroup
• A group of one or more views
• Provides the layout in which one can order the appearance and
sequence of contained views
• Derived from the base class android.view.ViewGroup
• Can be combined
• Examples: AbsoluteLayout, RelativeLayout, LinearLayout, TableLayout,
GridLayout, FrameLayout, ListView, GridView, ScrollView, WebView, etc.
7
Layout
• Responsible for arranging its child views (positions
and sizes), directly affecting the look and feel of an
application
• Several possibilities
• Manually specify absolute positions
• Manually specify relative positions
• Automate it
• Q: Pros and cons?
8
Layout: AWT/Swing vs. Android
• AWT/Swing
• Strategy design pattern (GoF)
• Layout manager for container
• Android
• Separate view group for each
layout, E.g.,
•
•
•
•
LinearLayout (~ FlowLayout)
GridLayout (~ GridLayout)
TableLayout (~ GridBagLayout?)
RelativeLayout
Container
LayoutManager
FlowLayout
GridLayout
• Q: Pros and cons?
9
Attributes of Views
• Required attributes
• layout_width
• layout_height
=> layout knows how to size a view
android:layout_height="wrap_content"
android:layout_width="match_parent" (previously "fill_parent“)
Start
Start
*can be specified in a measurement unit
10
Attributes of Views
• Other common attributes
•
•
•
•
•
•
•
•
Id (e.g., android:id=“@+id/startButton”)
layout_marginTop
layout_marginBottom
Q: How to refer it?
A: R.id.startButton
layout_marginLeft
layout_marginRight
layout_gravity (alignment: i.e., left, center, right)
layout_weight
...
11
Unit of Measurements
• Concern: devices with different densities (dpi, dot per
inch)
• Screen densities for Android
•
•
•
•
•
•
Low density (ldpi): 120 dpi
Medium density (mdpi): 160 dpi
High density (hdpi): 240 dpi
Extra high density (xhdpi): 320 dpi
Extra extra high density (xxhdpi): 480 dpi
Extra extra extra high density (xxxhdpi): 640 dpi
12
Different Units
• dp: density-independent pixel
• 160dp = 1" of physical screen size
• dp to screen pixels (px): px = dp x (dpi / 160)
• Same ratio on different devices; recommended
• sp: scale-independent pixel
• Similar to dp for specifying font size; recommended
• pt: point
• 1 pt = 1/72" of physical screen size; not recommended
• px: pixel
• Actual pixel of screen; not recommended
13
More on Layouts
Commonly used layouts
• RelativeLayout
• LinearLayout
• TableLayout
• GridLayout
• FrameLayout
14
15
LinearLayout
• Arranges its children either horizontally or vertically,
depending on the value of its orientation property,
(android:orientation="horizontal" or "vertical")
• Easiest layout to use
• Attributes for children
• layout_gravity="right“
• layout_weight="0.8"
gravity: specify how child views are positioned,
weight: specify how extra spaces are allocated, 80% of extra
space to the child (if total is 1).
16
Example
<LinearLayout
android:layout_width="match_parent"
android:layout_height=“match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_weight="0.4“
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal">
<edu.utep.cs.cs.4330.battleship.BoardView …>
…
</LinearLayout>
<edu.utep.cs.cs4330.battleship.TouchableBoardView
android:layout_weight=“0.6"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
</RelativeLayout>
BoardView
control
TouchableBoardView
17
RelativeLayout
• Most powerful layout available.
• Children positioned relative to each other or to their parent.
• Types of relationships:
• To the left, right, above or below the specified element
(layout_toLeftOf, layout_toRightOf, layout_above, layout_below)
• Aligned by the left, right, top or bottom edge of the specified
element (layout_alignLeft, layout_alignRight, layout_alignTop,
layout_alignBottom)
• Aligned by the left, right, top or bottom edge of a parent
(layout_alignParentLeft, layout_alignParentRight,
layout_alignParentTop, layout_alignParentBottom)
• Centered vertically, centered horizontally, centered vertically
and horizontally relative to its parent (layout_centerVertical,
layout_centerHorizontal, layout_centerInParent)
18
android:layout_alignParentTop=“true”
android:layout_alignParentLeft=“true”
android:layout_alignParentStart=“true”
android:layout_toRightOf=“@id/text2”
android:layout_alignBottom=“@id/text2”
android:layout_below=“@id/text1”
android:layout_alignLeft=“@id/text1”
android:layout_alignStart=“@id/text1”
android:layout_below=“@id/button”
android:layout_alignLeft=“@id/button”
android:layout_alignStart=“@id/button”
19
TableLayout
• Arrange child views in rows and columns
• Often used for organizing data content into tabular
form
• Subclass of LinearLayout.
• Use a TableRow element to add a row.
<TableLayout ...>
<TableRow> <TextView ../> <EditText .../> </TableRow>
<TableRow> <TextView ../> <Button .../> </TableRow>
</TableLayout>
20
GridLayout
• Places its children in a rectangular grid
• Can place children quickly without requiring a table
• Can place children in a controlled way by specifying a
row-and-column location or using layout_row and
layout_column attribute
• Horizontal vs vertical orientation
<GridLayout ...
android:columnCount=“2”
android:rowCount=“2”
android:orientation=“horizontal”>
<TextView ../> <TextView.../> <TextView…/> </TextVIew …/>
</GridLayout>
21
FrameLayout
• Placeholder on screen that can be used to display a
single view.
• Multiple views stacked in a frame layout, i.e.,
position children on top of each other.
22
Text Input and Output
• TextView: primarily for text output
• EditText: text input and editing by the user using
(soft) keyboard
View
TextView
EditText
Many Public Methods
• Refer to API docs
• TextView
•
•
•
•
•
void setText(CharSequence)
CharSequence getText() // String, StringBuffer, StringBuilder,…
int length() // number of chars
void addTextChangedListener(TextWatcher)
…
• EditText
• Editable getText() // Editable (Android) ---|> CharSequence
• void setSelection(int, int)
• …
• Q: Similar AWT/Swing widgets?
24
EditText Input Types
Text Field
inputType Property Value
Plain text
none
Person name
textPersonName
Password
textPassword
Password (Numeric)
numberPassword
E-mail
textEmailAddress
Phone
phone
Postal address
textPostalAddress
<EditText ...
androd:hint=“email address”
android:inputType=“textEmailAddress” />
25
Lab 2-1: Shipping Calculator
• Pages: 106-118
• Application settings
• Application name: Shipping Calculator
• Company name: cs4330.cs.utep.edu
• Android features
•
•
•
•
RelativeLayout
TextView
EditText
TextWatcher on EditText
• Image files from course website
26
Lab 2-1: What We Learned
• MVC separation
• UI design
•
•
•
•
res/layout/activity_main.xml
RelativeLayout, TextView, EditText
Background image
Custom launch icon
• Control
• MainActivity.java
• TextWatcher on EditText
• Model
• ShipItem.java
27
UI: RelativeLayout
layout_alignParentTop=“true”
layout_centerHorizontal=“True”
layout_below=“@id/textView”
…
layout_below=“@id/textView2”
layout_alignParentLeft=“true”
layout_alignParentStart=“True”
layout_below=“@id/textView2”
layout_alignParentRight=“true”
layout_alignParentEnd=“True”
28
UI (Cont.)
<EditText
view content (vs.
android:inputType=“number”
layout_gravity)
android:hint=“@string/zero”
android:gravity=“center_vertical|center_horizontal” … />
<RelativeLayout
android:background=“@drawable/shippingbck” … />
// AndroidManifest.xml
<manifest …>
<application
android:icon=“@mipmap/ic_launcher”
android:label=“@string/app_name”
…
29
MVC: Control
-weighET
EditText
MainActivity
ShipItem
-shipItem
setWeight
…
weightET.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
shipItem.setWeight((int) Double.parseDouble(s.toString()));
displayShipping();
}
public void afterTextChanged(Editable s) {
}
});
30
Views and Widgets
Many different views and widgets
• Basic views: simple, commonly used views, e.g.,
TextView, EditText, and Button
• Picker views: views for selecting from a list, e.g.,
TimePicker and DatePicker
• List views: views for displaying a long list of items,
e.g., Spinner and ListView
• Container views: views containing other views, e.g.,
RadioGroup, GridView, ScrollView, and VideoView.
31
32
Basic Views
•
•
•
•
•
•
•
•
•
•
TextView: displaying text (a.k.a. label)
Button: push-button widget
ImageButton: button that can also display an image
EditText: editing text (subclass of TextView)
AutoCompleteTextView: show a list of completion
suggestions
CheckBox: two-state button: checked or unchecked
RadioButton: two states: checked or unchecked
RadioGroup: grouping of radio buttons
ToggleButton: displaying checked/unchecked states using a
light indicator with text "On" and "Off“
…
33
Class Hierarchy
View (android.view)
TextView (android.widget)
Button
CompoundButton (abstract)
CheckBox
RadioButton
ToggleButton
EditText
ViewGroup (android.view)
LinearLayout (android.widget)
RadioGroup
34
Handling Events
• Register a handler after getting a reference to view
(use findViewById)
• Use XML onClick attribute for OnClickListener
View: setOnClickListener(View.OnClickListener)
*work for all views including various buttons
RadioGroup: setOnCheckedChangeListener(OnCheckedChangeListener)
<Button
...
android:onClick=“buttonClicked"/>
35
ProgressBar
• Visual indicator of progress in a given operation
• Default mode
• Indefinite/indeterminate meaning that it shows a cyclic animation
• Useful for tasks having no clear indication when they will be
completed, e.g., sending data to web service
• Termination: setVisibility(int) -- not synchronized
0: View.VISIBLE; 4: View.INVISIBLE; 8: View.GONE
• Communication with progress bar: runOnUiThread(Runnable),
Handler.post(Runnable), AsyncTask
• Customization
• Use style attribute: style="?android:attr/progressBarStyleHorizontal"
• Control:
ProgressBar.setMax(int)
-- synchronized
ProgressBar.setProgress(int) -- synchronized
ProgressBar.dismiss()
-- synchronized
36
ViewGroup
• Container of view objects
• Special view to hold groups of views
• Invisible that organizes child views
37
RadioGroup and RadioButton
• A radio button is specifically used when a single item
from a collection of items must be made.
• If a radio button is already selected, it will be deselected when another radio button in the collection is
selected.
• Do Lab 2-2 Burger Calorie Calculator (p. 127)
38
Adaptive Design Concepts - Screens
and Orientations
• Challenge
Diversity of devices such as screen size and density, e.g.,
many variations in screen sizes that are available on the
market at any given time.
• Adaptive design
• Adaptation of a layout design to fit an individual screen
size and or orientation.
• Important to Android because it supports flexibility
when designing an app that can work on multiple
devices.
Adapting to Different Screen Sizes
• Use screen size qualifiers, e.g., layout-xlarge
Screen sizes
•
•
•
•
small: 426dp x 320dp (< 4”)
normal: 470dp x 320dp (~ 4”)
large: 640dp x 480dp (4”-7”)
xlarge: 960dp x 720dp (7”-10”)
Q: Any problem?
New qualifier (since Android 3.2)
sw<N>dp (smallest width), w<N>dp, h<N>dp, e.g.,
•
•
•
•
sw320dp typical phone
sw480dp tweener tablet
sw600dp 7" tablet (i.e., layout-sw600dp)
sw720dp 10" tablet
40
Adapting to Screen Orientation
• Techniques for handling screen orientation changes
• Fix or force screen orientation (portrait or landscape)
• Adapt to orientation changes (i.e., resize and reposition)
• Forcing screen orientation
• In AndroidManifest.xml
android:screenOrientation=“landscape” for each activity
• In activity class
setRequestOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
41
Adapting to Orientation Changes
• Two techniques
• Anchoring: anchor views to four edges of the screen (use
RelativeLayout)
• Resizing and repositioning
• Resizing and repositioning
• Resizing and repositioning views according to the current
screen orientation
• Use layout qualifier and multiple XML files, e.g.,
res/layout/activity_main.xml (for all modes)
res/layout-port/activity_main.xml (for portrait mode)
res/layout-land/activity_main.xml (for landscape mode)
42
Detecting Orientation Changes
• Use WindowManager to get the current display and
compare display width and height, e.g.,
WindowManager wm = getWindowManager();
Display d = wm.getDefaultDisplay();
if (d.getWidth() > d.getHeight())
... landscape
else
... portrait
43
Lab 2-3: Shipping Calculator II
• Pages 144-153; portrait and landscape
44
Container Views
• Containers (view group) for other views, e.g.,
• ListView: items displayed in a vertically scrolling list
• GridView: items displayed in a two-dimensional scrolling grid.
• ExpandableListView: extension of a ListView to support two
levels
• …
45
Providing Data to Container Views
• Challenge
• Many different data sources, e.g., arrays, collections,
and database
• Many different ways of displaying them, e.g., Spinner,
ListView, and GridView
• Q: How to bind them together?
• Q: Any design pattern for this?
Array
List
Database
…
46
Adapter (GoF Pattern)
• Bind a data source to an container view (AdapterView)
• Provides a common interface to the data model behind an
AdapterView such as ListView
• Responsible for:
• Accessing the data to be supplied to a container widget and
• Converting the individual elements of data into a specific view
• Behaves as a middleman between the data source and the
adapterView.
AdapterView
ListView
<<interface>>
Adapter
ArrayAdapter
array
47
ListView
• Display a list of items in a vertically scrolling list
• Providing a list of data to display
setAdaper(ListAdapter)
• ListAdapter: subinterface of Adapter with many
subclasses including:
•
•
•
•
•
•
ArrayAdapter<T>
BaseAdapter (abstract)
CursorAdapter (abstract)
SimpleBaseAdapter
SimpleCursorAdapter
…
• Listener: OnItemSelectedListener
48
ListView (Cont.)
• Customization
• setChoiceMode(int): none
(ListView.CHOICE_MODE_NONE), single, multiple
• setTextFilterEnabled(boolean): let the view filter to
match what is typed on the keypad
• setItemChecked(int, boolean)
49
ListView (Cont.)
• Storing and retrieving items from strings.xml
getResources().getStringArray(R.array.my_array)
// in strings.xml
<string-array name=“my_array”>
<item>cake</item>
<item>pie</item>
<item>ice cream</item>
</string-array>
50
Example: List of Deserts
• Section 9.6 Adapter and AdapterView (p. 765-769)
• ListView and ArrayAdapter
• Variation: Store names in
strings.xml and use
getResources().getStringArray
(int) to retrieve them
51
Do Lab 2-2, 2-4, or 2-5
•
•
•
•
•
Lab 2-2 Burger Calorie Calculator (p. 127) - RadioButton, CheckBox, SeekBar
Lab 2-4 Simple Calculator (p. 155) - TableLayout
Lab 2-5 Renaissance Paintings (p. 173) – ScrollView
Image files from course website.
Show your work (app) to TA.
52