Download Android User Interface (UI) Layouts By Shinping R. Wang

Document related concepts
no text concepts found
Transcript
Android User Interface (UI)
Layouts
By Shinping R. Wang
CSIE Dept. of Da‐yeh University
Reference

The following discussion is excerpted from
1.
Android Developer:
http://developer.android.com/guide/topics/ui/declaringlayout.html
2.
About the anonymous class, see Java in a Nutshell Chapter 3.
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
Layouts

Have you play with table in word processing packages?


Layout is just something like that.
It gives frames for storing cell.
Layouts

Two ways of declaring layout

Declare UI elements in XML.




Statically
Easy to visualize and program
In xml file
Instantiate layout elements at runtime.

Dynamically at run time
Layouts

The element and attributes identifiers of the XML file is closely
resemblance to their counter part in class. For example
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_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>

Corresponding to element TextView and Button, we have classes
TextView and Button in the same name. We also have a method
getText() correspond to the attribute text in each.
Write the Layouts XML

A View hierarchy consists of views and layouts in tree
with a root view
Layouts

For example, here's an XML layout that uses a vertical
LinearLayout to hold a TextView and a Button:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_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>
Layouts

The layout file has to be in


.xml extension, and
Save in res/layout/ directory,
so it will be properly compiled.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_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>
Load the XML resources

Compile


application, each XML layout file of your application is
compiled into a View resource.
Load



The compiled view is load inside of Activity.onCreate()
callback
By calling setContentView(),
Where the reference of the view R.layout.layout_file_name is
passed.
Load the XML resources

Here is an code example,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
Attributes

All views are subclass of View and ViewGroup


They inherit attributes from View and ViewGroup
However, there are attributes that are pertains to special view.
ID

Any View object may have an integer ID associated with it,
to uniquely identify the View within the tree.

referenced as an integer in the Android, but in the layout XML
file as a string,
android:id="@+id/my_button"




attribute : “android:id”
@: indicates that the XML parser should parse and expand the rest
of the ID string and identify it as an ID resource.
+ : a new resource name that must be created and added to our
resources (in the R.java file).
The name of the resource is “my_button”
ID

When referencing an Android resource


Skipped the “+” sign and use the resource name directly
Referencing an android resource

with the package name android in place to reference an ID from the
android.R resources
android:id="@android:id/my_button"

Referencing an local resources

with the local package name by default to reference an ID from R.java
android:text="@string/my_button_text"/
ID

Steps in creating views and referencing them from the
application
1.
Define a view/widget in the layout file and assign it a unique
ID:
<Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>
2.
Then create an instance of the view object and capture it
from the layout (typically in the onCreate() method):
Button myButton = (Button) findViewById(R.id.my_button);
Layout Parameters

XML layout attributes named layout_something define
layout parameters for the View that are appropriate for
the ViewGroup in which it resides.

For example, layout_width and layout_height
Layout Parameters

Values of attributes layout_width and layout_height can
be one of these:



wrap_content : tells your view to size itself to the dimensions
required by its content
fill_parent: (renamed match_parent in API Level 8) tells your
view to become as big as its parent view group will allow.
A value: in density-independent pixel units (dp),
See also available resources: http://developer.android.com/guide/topics/resources/available-resources.html#dimension
Layout Position (as well as any view position)

View’s shape, location, and dimension
Left (x) and top (y)
coordinates the view
relative to its parent
width
height
Shape is always in rectangle and all unit is in pixel.
Size, padding, and Margins

Width and Height of View

measured width and measured height



These dimensions define how big a view wants to be within its parent.
obtained by calling getMeasuredWidth() and getMeasuredHeight().
width and height(or sometimes drawing width and drawing
height)


the actual size of the view on screen, at drawing time and after layout.
obtained by calling getWidth() and getHeight().
Size, padding, and Margins

Padding



Is used to offset the content of the view by a specific amount
of pixels.
can be set using the setPadding(int, int, int, int) method and
queried by calling getPaddingLeft(), getPaddingTop(),
getPaddingRight() and getPaddingBottom().
Size, padding, and Margins

Margins

Is for ViewGroup (View does not have setting for margins)
See also the dimension type: http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
Size, padding, and Margins

Units



DP (Density Independent Pixels), based on 160dpi, scaled to
the real screen density.
SP (Scale-independent Pixels), for font size scaling.
Through scaling, the appearance of an icon will be the same on
different screens
Scale up/down from the baseline design
See also the dimension type: http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
Common Layout

These are commonly seen layout and are subclass of
ViewGroup
Linear Layout
Relative Layout
Web Layout
Note: To make your App runs faster, keep your layout hierarchy as shallow as possible (a wide view hierarchy is better than a
deep view hierarchy).
Linear Layout

aligns all children in a single direction, vertically or
horizontally.


layout direction is given by the android:orientation attribute.
A LinearLayout respects margins between children and the
gravity (right, center, or left alignment) of each child.
Linear Layout
horizontal
Linear Layout
vertical
Linear Layout

Layout weight



The importance of the view among its sibling
The larger the number the greater the impotency
use android:layout_weight attribute, the default value is 0
Equally weighted/space children
To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each
view to “0dp” (for a vertical layout) or the android:layout_width of each view to “0dp” (for a horizontal layout). Then set the
android:layout_weight of each view to “1“.
Linear Layout

For details about the attributes available to each child
view of a LinearLayout, see LinearLayout.LayoutParams.
Linear Layout

An example.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/to“ />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/subject" />
<EditText
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/message" />
Linear Layout

An example.
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity=“center_vertical"
android:text="@string/send" />
</LinearLayout>
Linear Layout

string resources of local package are defomed under the
directory of res/values/strings.xml
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="to">To</string>
<string name="subject">Subject</string>
<string name="message">Message</string>
<string name="send">SEND</string>
</resources>
Linear Layout

The result
Relative Layout

RelativeLayout displays child views in relative positions.
A
B
C
B and C is underneath the A,
B is to the left of C, ……
Relative Layout


it can eliminate nested view groups and keep your layout
hierarchy flat, which improves performance.
If you find yourself using several nested LinearLayout groups,
you may be able to replace them with a single RelativeLayout.
Linear layout A
A
Linear layout B nested in A
B
Two nested Linear Layouts
One relative Layout
C
Positioning Views



Child views specify theirs position relative to the parent view
or to each other (specified by ID).
By default, all child views are drawn at the top-left of the
layout
All Positioning attributes are given in class of
RelativeLayout.LayoutParams.
Positioning Views


All Positioning attributes are given in class of
RelativeLayout.LayoutParams.
Just to name a few,
Attributes
Description
android:layout_alignParentTop
If "true", makes the top edge of this view
match the top edge of the parent.
android:layout_centerVertical
If "true", centers this child vertically within its
parent.
android:layout_below
Positions the top edge of this view below the
view specified with a resource ID.
android:layout_toRightOf
Positions the left edge of this view to the right
of the view specified with a resource ID.
The value for each layout property is either a boolean to enable a layout position relative to the
parent RelativeLayout or an ID that references another view in the layout against which the view
should be positioned.
Positioning Views

For example,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<Spinner android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
Positioning Views

For example,
<Spinner android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />
</RelativeLayout>
Building layouts with an adapter

AdapterView

When the content of layout is dynamic or not pre-determined,
use a layout that subclasses AdapterView to populate the
layout with views at runtime.
Building layouts with an adapter

Adapter


behaves as a middle-man/bridge between the data source and
the AdapterView layout, more specifically
retrieves the data (from a source such as an array or a
database query) and converts each entry into a view that can
be added into the AdapterView layout.
Building layouts with an adapter

Adapter


In short, Adapter binds data to its layout where
layout is a subclass of the class AdapterView
Building layouts with an adapter

Adapter

Subclass of AdapterView:


Known Direct Subclasses: AbsListView, AbsSpinner,
AdapterViewAnimator,
Known Indirect Subclasses: AdapterViewFlipper, ExpandableListView,
Gallery, GridView, ListView, Spinner, StackView
Maybe a
GridView,
ListView,
Spinner, or others.
Building layouts with an adapter

Common layouts backed by an adapter include:
List View:
Displays a scrolling single column list.
Grid View:
Displays a scrolling grid of columns and rows.
Building layouts with an adapter

Filling an adapter view with data


Binds the AdapterView instance to an Adapter
Uses the Adapter to retrieve data from an external source and
creates a View that represents each data entry.
Building layouts with an adapter

Subclass of Adapter


To retrieve data and bind to the AdapterView
There are several of them, the two most commonly used are:











ArrayAdapter
SimpleCursorAdapter
ArrayAdapter<T>,
BaseAdapter,
CursorAdapter,
HeaderViewListAdapter,
ListAdapter,
ResourceCursorAdapter,
SimpleAdapter,
SpinnerAdapter,
WrapperListAdapter
Building layouts with an adapter

ArrayAdapter
extends BaseAdapter
implements Filterable
java.lang.Object
↳ android.widget.BaseAdapter
↳ android.widget.ArrayAdapter<T>

Constructor (one among the many)
public ArrayAdapter (Context context, int textViewResourceId, T[] objects)
Parameters
context
The current context.
textViewResourceId The resource ID for a layout file containing a TextView to use when
instantiating views.
objects
The objects to represent in the ListView.
Building layouts with an adapter


ArrayAdapter
For example,

if you have an array of strings you want to display in a ListView,
initialize a new ArrayAdapter using a constructor to specify the
layout for each string and the string array:
ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myStringArray);

Argument
context
The current context. i.e. “this”
textViewResource Id
android.R.layout.simple_list_item_1 (we use a textView
instead)
objects
myStringArray
Building layouts with an adapter


ArrayAdapter
For example,

After instantiating and configuring the ArrayAdapter, creates
an reference to a prebuild ListView and associates the View
with the Adapter.
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
Building layouts with an adapter

A example


This example is form Api Demos -> Animation -> View Flip
What it does is flipping two lists of texts (one in English and
the other in French.) Flipping is done using animation.
Specifically, the English list and French list exchange
alternatively when ever the Botton “Flip” is clicked. The
change is in animation that emulating a fan slow rotating along
the axis of y.
Building layouts with an adapter

A example form
/ApiDemos/src/com/example/android/apis/animation/Lis
tFlipper.java
Lien 47 and line 55 define and instantiate two
array of String. These String[] server as data that
to be filled into the ViewLists dynamically.
Building layouts with an adapter
Lien 73 and line 74 declare two ListViews.
They use the resources defined in the
layout Rotating_list.xml.
Line 77 and 80 instantiated two
ArrayAdapter<String> for data
LIST_STRINGS_En and LIST_STRING_FR
respectively.
Line 83 and 84 set the adapter to the
corresponding ListViews.
Line 87-92, dereferencing the Button
defined in the Rotating_list.xml and
implement a anonymous class click
listener for it
Building layouts with an adapter
This part is the animation part and is not
our main concern here. Still,
Line 100-106 taken care of the toggling
of the ListView.
Line 107- 123 taken care of the
animation part of the APP and will be
discussed in the future.
Building layouts with an adapter

An example

/ApiDemos/res/layout/rotating_list.xml
Noticed that, on line 37 where the
visibility has been set to gone which
means the ListView will not be drawn at
the start of the of the app.
Building layouts with an adapter

ArrayAdapter


To customize the appearance of each item you can override
the toString()† (which is the default) method for the objects in
your array.
to create a view for each item that's something other than a
TextView (also the default setting), extend the ArrayAdapter
class and override getView() ‡ to return the type of view you
want for each item.
†toString() is a method inherited from Object(). To override the method, you will have to extend the class ArrayAdapter and
in that class override the method toString.
‡ An public method of ArrayAdapter with signature public View getView (int position, View convertView, ViewGroup parent).
The API does not disclosed any information about the use of the method through.
Building layouts with an adapter

Remarks

Up to this point, we have seen using a a-prior xml layout and
set the view by setContentView() method to associate the
layout with the activity on create. You can revised the view
using Adapter dynamically.
Building layouts with an adapter

Remarks

You can also define a layout dynamically that use the addView()
from class ViewGroup to add views into the layout. Then use
the setContentView() to register the layout to the activity.
†As stated in the Activity section of the Android developer API that “However, you can also create new Views in your activity
code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the root
ViewGroup to setContentView().”
Building layouts with an adapter

SimpleCursorAdaptor

Use this adapter when your data comes from a Cursor.
Building layouts with an adapter

SimpleCursorAdaptor

When using SimpleCursorAdapter, you must specify a layout to
use for each row in the Cursor and which columns in the
Cursor should be inserted into which views of the layout.
view
layout
Adapter defines the mapping
Cursor
row
column
Building layouts with an adapter

SimpleCursorAdaptor

For example, if you want to create a list of people's names and
phone numbers, you can perform a query that returns a Cursor
containing a row for each person and columns for the names
and numbers. You then create a string array specifying which
columns from the Cursor you want in the layout for each result
and an integer array specifying the corresponding views that
each column should be placed:
view
layout
Adapter defines the mapping
row
Cursor
Building layouts with an adapter

SimpleCursorAdaptor

For example, if you want to create a list of people's names and
phone numbers, you can perform a query that returns a Cursor
containing a row for each person and columns for the names
and numbers. You then create a string array specifying which
columns from the Cursor you want in the layout for each result
and an integer array specifying the corresponding views that
each column should be placed:
view
layout
Adapter defines the mapping
row
Cursor
Building layouts with an adapter

SimpleCursorAdaptor
For example, if you want to create a list of people's names and
String[]
fromColumns
= { ContactsContract.Data.DISPLAY_NAME,
phone
numbers,
you can perform a query that returns a Cursor
ContactsContract.CommonDataKinds.Phone.NUMBER};
a row R.id.phone_number};
for each person and columns for the names
int[]containing
toViews = {R.id.display_name,
and numbers. You then create a string array specifying which
columns from the Cursor you want in the layout for each result
and an integer array specifying the corresponding views that
each column should be placed:

view
layout
Adapter defines the mapping
row
Cursor
Building layouts with an adapter

SimpleCursorAdaptor

When you instantiate the SimpleCursorAdapter, pass the
layout to use for each result, the Cursor containing the results,
and these two arrays:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);
view
layout
Adapter defines the mapping
row
Cursor
List View


a view group that displays a list of scrollable items.
an Adapter pulls content from a source such as an array
or database query and converts each item result into a
view that's placed into the list automatically.
List View

Using a loader
List View

An example

The following example uses ListActivity, which is an activity
that includes a ListView as its only layout element by default. It
performs a query to the Contacts Provider for a list of names
and phone numbers.
Building layouts with an adapter

Handling click events

You can respond to click events on each item in an
AdapterView by implementing the
AdapterView.OnItemClickListener interface. For example:
// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Do something in response to the click
} };
listView.setOnItemClickListener(mMessageClickedHandler);
Building layouts with an adapter

Handling click events

You can respond to click events on each item in an
AdapterView by implementing the
AdapterView.OnItemClickListener interface. For example:
// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Do something in response to the click
} };
listView.setOnItemClickListener(mMessageClickedHandler);