SlideShare a Scribd company logo
Welcome to vibrant technologies
and computers.
1Vibrant Technology & Computers
Android Development
2Vibrant Technology & Computers
Content
• These are the sections in this unit:
• Introduction
• Layouts (Taken from Resources Section of
Tutorials)
• Layouts (Taken from Layouts Section of
Tutorials)
• Linear Layout
• Relative Layout
• List View
• Grid View
3Vibrant Technology & Computers
4Vibrant Technology & Computers
• As usual, the decision to present this material at
this point is based partially on background ideas
found in the book
• The contents of the overheads consist largely of
material taken from the online tutorials, with
occasional commentary by me
• The commentary will either be introduced as
commentary or appear in square brackets
• If not set off in this way, the content is taken from
the tutorials
5Vibrant Technology & Computers
• As mentioned before, what you’re getting is
an idiosyncratic path through some of the
various topics covered in the tutorials
• The goal is to cover enough of the items
involved in sufficient depth so that the
perceptive learner could pick up more when
needed
6Vibrant Technology & Computers
Layouts (Taken from Resources Section
of Tutorials)
7Vibrant Technology & Computers
• Layout Resource
• A layout resource defines the architecture for the UI in
an Activity or a component of a UI.
• file location:
• res/layout/filename.xml
• The filename will be used as the resource ID.
• compiled resource datatype:
• Resource pointer to a View (or subclass) resource.
• resource reference:
• In Java: R.layout.filename
• In XML: @[package:]layout/filename
8Vibrant Technology & Computers
• Note:
• The root element can be either a ViewGroup,
a View, or a <merge> element, but there must
be only one root element and it must contain
the xmlns:android attribute with the android
namespace as shown.
9Vibrant Technology & Computers
• elements:
• <ViewGroup>
• A container for other View elements.
• There are many different kinds of ViewGroup
objects and each one lets you specify the layout
of the child elements in different ways.
• Different kinds of ViewGroup objects include
LinearLayout, RelativeLayout, and FrameLayout.
• You should not assume that any derivation of
ViewGroup will accept nested Views.
10Vibrant Technology & Computers
• Some ViewGroups are implementations of the
AdapterView class, which determines its
children only from an Adapter.
• [This is not the same as an adapter class in the
Java API.
• It has more in common with the adapter
design pattern of CSCE 202.
• More information will be given later in this
unit.]
11Vibrant Technology & Computers
• attributes:
• android:id
• Resource ID.
• A unique resource name for the element,
which you can use to obtain a reference to the
ViewGroup from your application.
• See more about the value for android:id
below.
12Vibrant Technology & Computers
• android:layout_height
• Dimension or keyword. Required.
• The height for the group, as a dimension value
(or dimension resource) or a keyword
("fill_parent" or "wrap_content").
• See the valid values below.
13Vibrant Technology & Computers
• android:layout_width
• Dimension or keyword. Required.
• The width for the group, as a dimension value
(or dimension resource) or a keyword
("fill_parent" or "wrap_content").
• See the valid values below.
14Vibrant Technology & Computers
• More attributes are supported by the
ViewGroup base class, and many more are
supported by each implementation of
ViewGroup.
• For a reference of all available attributes, see
the corresponding reference documentation
for the ViewGroup class (for example, the
LinearLayout XML attributes).
15Vibrant Technology & Computers
• <View>
• An individual UI component, generally referred to as a
"widget".
• Different kinds of View objects include TextView, Button,
and CheckBox.
• attributes:
• android:id
• Resource ID.
• A unique resource name for the element, which you can
use to obtain a reference to the View from your application.
• See more about the value for android:id below.
16Vibrant Technology & Computers
• android:layout_height
• Dimension or keyword. Required.
• The height for the element, as a dimension
value (or dimension resource) or a keyword
("fill_parent" or "wrap_content").
• See the valid values below.
17Vibrant Technology & Computers
• android:layout_width
• Dimension or keyword. Required.
• The width for the element, as a dimension
value (or dimension resource) or a keyword
("fill_parent" or "wrap_content").
• See the valid values below.
18Vibrant Technology & Computers
• More attributes are supported by the View
base class, and many more are supported by
each implementation of View.
• Read Layouts for more information.
• For a reference of all available attributes, see
the corresponding reference documentation
(for example, the TextView XML attributes).
19Vibrant Technology & Computers
• <requestFocus>
• Any element representing a View object can
include this empty element, which gives its
parent initial focus on the screen.
• You can have only one of these elements per
file.
20Vibrant Technology & Computers
• <include>
• Includes a layout file into this layout.
• attributes:
• layout
• Layout resource. Required.
• Reference to a layout resource.
21Vibrant Technology & Computers
• android:id
• Resource ID.
• Overrides the ID given to the root view in the
included layout.
• android:layout_height
• Dimension or keyword.
• Overrides the height given to the root view in the
included layout.
• Only effective if android:layout_width is also
declared.
22Vibrant Technology & Computers
• android:layout_width
• Dimension or keyword.
• Overrides the width given to the root view in the
included layout.
• Only effective if android:layout_height is also
declared.
• You can include any other layout attributes in the
<include> that are supported by the root element
in the included layout and they will override
those defined in the root element.
23Vibrant Technology & Computers
• Caution:
• If you want to override layout attributes using
the <include> tag, you must override both
android:layout_height and
android:layout_width in order for other layout
attributes to take effect.
24Vibrant Technology & Computers
• Another way to include a layout is to use
ViewStub.
• It is a lightweight View that consumes no
layout space until you explicitly inflate it, at
which point, it includes a layout file defined by
its android:layout attribute.
• For more information about using ViewStub,
read Loading Views On Demand.
25Vibrant Technology & Computers
• <merge>
• An alternative root element that is not drawn in the
layout hierarchy.
• Using this as the root element is useful when you know
that this layout will be placed into a layout that already
contains the appropriate parent View to contain the
children of the <merge> element.
• This is particularly useful when you plan to include this
layout in another layout file using <include> and this
layout doesn't require a different ViewGroup container.
• For more information about merging layouts, read Re-
using Layouts with <include/>.
26Vibrant Technology & Computers
• Value for android:id
• For the ID value, you should usually use this
syntax form: "@+id/name".
• The plus symbol, +, indicates that this is a new
resource ID and the aapt tool will create a new
resource integer in the R.java class, if it
doesn't already exist. For example:
• <TextView android:id="@+id/nameTextbox"/>
27Vibrant Technology & Computers
• The nameTextbox name is now a resource ID
attached to this element.
• You can then refer to the TextView to which the
ID is associated in Java:
• findViewById(R.id.nameTextbox);
• This code returns the TextView object.
• However, if you have already defined an ID
resource (and it is not already used), then you
can apply that ID to a View element by excluding
the plus symbol in the android:id value.
28Vibrant Technology & Computers
• Value for android:layout_height and
android:layout_width:
• The height and width value can be expressed
using any of the dimension units supported by
Android (px, dp, sp, pt, in, mm) or with the
following keywords:
29Vibrant Technology & Computers
Value Description
match_parent
Sets the dimension to match that of the
parent element. Added in API Level 8 to
deprecate fill_parent.
fill_parent
Sets the dimension to match that of the
parent element.
wrap_content
Sets the dimension only to the size
required to fit the content of this
element.
30Vibrant Technology & Computers
• Custom View elements
• You can create your own custom View and
ViewGroup elements and apply them to your
layout the same as a standard layout element.
• You can also specify the attributes supported
in the XML element.
• To learn more, see the Custom Components
developer guide.
31Vibrant Technology & Computers
• example:
• XML file saved at res/layout/main_activity.xml: <?xml
version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
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>
32Vibrant Technology & Computers
• This application code will load the layout for an
Activity, in the onCreate() method:
• public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
• [Read it again for the second time…
• The point is that the onCreate() method starts with a
setContentView() call.
• This is what connects a Java app file to its layout file.]
33Vibrant Technology & Computers
8.3 Layouts (Taken from Layouts
Section of Tutorials)
34Vibrant Technology & Computers
• Layouts
• A layout defines the visual structure for a user
interface, such as the UI for an activity or app
widget.
• You can declare a layout in two ways:
• [1] Declare UI elements in XML.
• Android provides a straightforward XML
vocabulary that corresponds to the View classes
and subclasses, such as those for widgets and
layouts.
35Vibrant Technology & Computers
• [2] Instantiate layout elements at runtime.
• Your application can create View and
ViewGroup objects (and manipulate their
properties) programmatically.
36Vibrant Technology & Computers
• The Android framework gives you the flexibility to
use either or both of these methods for declaring
and managing your application's UI.
• For example, you could declare your application's
default layouts in XML, including the screen
elements that will appear in them and their
properties.
• You could then add code in your application that
would modify the state of the screen objects,
including those declared in XML, at run time.
37Vibrant Technology & Computers
• 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.
• Your UI descriptions are external to your
application code, which means that you can
modify or adapt it without having to modify
your source code and recompile.
38Vibrant Technology & Computers
• For example, you can create XML layouts for
different screen orientations, different device
screen sizes, and different languages.
• Additionally, declaring the layout in XML
makes it easier to visualize the structure of
your UI, so it's easier to debug problems.
• As such, this document focuses on teaching
you how to declare your layout in XML.
39Vibrant Technology & Computers
• If you're interested in instantiating View
objects at runtime, refer to the ViewGroup
and View class references.
40Vibrant Technology & Computers
• In general, the XML vocabulary for declaring
UI elements closely follows the structure and
naming of the classes and methods, where
element names correspond to class names
and attribute names correspond to methods.
• In fact, the correspondence is often so direct
that you can guess what XML attribute
corresponds to a class method, or guess what
class corresponds to a given xml element.
41Vibrant Technology & Computers
• However, note that not all vocabulary is
identical.
• In some cases, there are slight naming
differences.
42Vibrant Technology & Computers
• For example, the EditText element has a text
attribute that corresponds to
EditText.setText().
• [They got their explanations slightly out of
order.
• The text attribute and setText() method are an
example of correspondence.
• The are not intended as an example of a case
with a slight difference.]
43Vibrant Technology & Computers
• Tip:
• Learn more about different layout types in
Common Layout Objects.
• There are also a collection of tutorials on
building various layouts in the Hello Views
tutorial guide.
44Vibrant Technology & Computers
• Write the XML
• Using Android's XML vocabulary, you can
quickly design UI layouts and the screen
elements they contain, in the same way you
create web pages in HTML — with a series of
nested elements.
• Each layout file must contain exactly one root
element, which must be a View or ViewGroup
object.
45Vibrant Technology & Computers
• Once you've defined the root element, you
can add additional layout objects or widgets
as child elements to gradually build a View
hierarchy that defines your layout.
• For example, here's an XML layout that uses a
vertical LinearLayout to hold a TextView and a
Button:
46Vibrant Technology & Computers
• <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
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>
47Vibrant Technology & Computers
• After you've declared your layout in XML, save
the file with the .xml extension, in your
Android project's res/layout/ directory, so it
will properly compile.
• More information about the syntax for a
layout XML file is available in the Layout
Resources document.
48Vibrant Technology & Computers
• Load the XML Resource
• When you compile your application, each XML
layout file is compiled into a View resource.
• You should load the layout resource from your
application code, in your Activity.onCreate()
callback implementation.
49Vibrant Technology & Computers
• Do so by calling setContentView(), passing it
the reference to your layout resource in the
form of:
• R.layout.layout_file_name
• For example, if your XML layout is saved as
main_layout.xml, you would load it for your
Activity like so:
50Vibrant Technology & Computers
• public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
• The onCreate() callback method in your
Activity is called by the Android framework
when your Activity is launched (see the
discussion about lifecycles, in the Activities
document).
51Vibrant Technology & Computers
• [It may be worth noting something here:
• You can access layouts directly using their name
as given in R.java:
• setContentView(R.layout.main_layout);
• Contrast this with how you acquire a reference to
an individual view in a layout:
• EditText myEditText = (EditText)
findViewById(R.id.input_message_view);
52Vibrant Technology & Computers
• Or how you access a resource:
• Resources res = getResources();
• String[] prompts = res.getStringArray(R.array.prompt_array);
• int colorIndex = res.getInteger(R.integer.numberInColorCycle);
• ]
53Vibrant Technology & Computers
• Attributes
• Every View and ViewGroup object supports
their own variety of XML attributes.
• Some attributes are specific to a View object
(for example, TextView supports the textSize
attribute), but these attributes are also
inherited by any View objects that may extend
this class.
54Vibrant Technology & Computers
• Some are common to all View objects,
because they are inherited from the root View
class (like the id attribute).
• And, other attributes are considered "layout
parameters," which are attributes that
describe certain layout orientations of the
View object, as defined by that object's parent
ViewGroup object.
55Vibrant Technology & Computers
• ID
• Any View object may have an integer ID
associated with it, to uniquely identify the
View within the tree.
• When the application is compiled, this ID is
referenced as an integer, but the ID is typically
assigned in the layout XML file as a string, in
the id attribute.
56Vibrant Technology & Computers
• This is an XML attribute common to all View
objects (defined by the View class) and you
will use it very often.
• The syntax for an ID, inside an XML tag is:
• android:id="@+id/my_button"
57Vibrant Technology & Computers
• The at-symbol (@) at the beginning of the
string indicates that the XML parser should
parse and expand the rest of the ID string and
identify it as an ID resource.
• The plus-symbol (+) means that this is a new
resource name that must be created and
added to our resources (in the R.java file).
58Vibrant Technology & Computers
• There are a number of other ID resources that
are offered by the Android framework.
• When referencing an Android resource ID, you
do not need the plus-symbol, but must add
the android package namespace, like so:
• android:id="@android:id/empty"
59Vibrant Technology & Computers
• With the android package namespace in place,
we're now referencing an ID from the android.R
resources class, rather than the local resources
class.
• [If accurate, this is an interesting statement.
• We’re being told something about the meaning
of the syntax.
• Java app code depends on R.java.
• After the related project files are built, layout and
other resource files also depend on R.java for
id’s.]
60Vibrant Technology & Computers
• In order to create views and reference them
from the application, a common pattern is to:
• 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"/>
61Vibrant Technology & Computers
• 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);
• [You’re not creating an instance of the object.
• You’re recovering a reference to the object as
defined/created in the layout file.]
62Vibrant Technology & Computers
• Defining IDs for view objects is important
when creating a RelativeLayout.
• In a relative layout, sibling views can define
their layout relative to another sibling view,
which is referenced by the unique ID.
63Vibrant Technology & Computers
• An ID need not be unique throughout the
entire tree, but it should be unique within the
part of the tree you are searching (which may
often be the entire tree, so it's best to be
completely unique when possible).
• [Clowns: Just make them globally unique.]
64Vibrant Technology & Computers
• Layout Parameters
• XML layout attributes named layout_something
define 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 property types that define
the size and position for each child view, as
appropriate for the view group.
65Vibrant Technology & Computers
• As you can see in figure 1, the parent view group
defines layout parameters for each child view
(including the child view group).
• [Following overhead]
• [General note on this topic:
• What they seem to be saying is that a parent in
effect defines what kinds of parameters its
children will have.
• It’s up to the children to use values which are
appropriate to the parameters defined in their
parents.]
66Vibrant Technology & Computers
Figure 1. Visualization of a view hierarchy with
layout parameters associated with each view.
67Vibrant Technology & Computers
• Note that every LayoutParams subclass has its
own syntax for setting values.
• Each child element must define LayoutParams
that are appropriate for its parent, though it may
also define different LayoutParams for its own
children.
• All view groups include a width and height
(layout_width and layout_height), and each view
is required to define them.
• Many LayoutParams also include optional
margins and borders.
68Vibrant Technology & Computers
• You can specify width and height with exact
measurements, though you probably won't want
to do this often.
• More often, you will use one of these constants
to set the width or height:
• 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.
69Vibrant Technology & Computers
• In general, specifying a layout width and height
using absolute units such as pixels is not
recommended.
• Instead, using relative measurements such as
density-independent pixel units (dp),
wrap_content, or fill_parent, is a better
approach, because it helps ensure that your
application will display properly across a variety
of device screen sizes.
• The accepted measurement types are defined in
the Available Resources document.
70Vibrant Technology & Computers
• Layout Position
• The geometry of a view is that of a rectangle.
• A view has a location, expressed as a pair of
left and top coordinates, and two dimensions,
expressed as a width and a height.
• The unit for location and dimensions is the
pixel.
71Vibrant Technology & Computers
• It is possible to retrieve the location of a view
by invoking the methods getLeft() and
getTop().
• The former returns the left, or X, coordinate of
the rectangle representing the view.
• The latter returns the top, or Y, coordinate of
the rectangle representing the view.
• [Notice the similarity with the bounding box in
Java graphics.]
72Vibrant Technology & Computers
• These methods both return the location of the
view relative to its parent.
• For instance, when getLeft() returns 20, that
means the view is located 20 pixels to the
right of the left edge of its direct parent.
• [Keep in mind that this is of pretty remote
usefulness.
• In general we’d like to avoid hardcoding
dimensional values.]
73Vibrant Technology & Computers
• In addition, several convenience methods are
offered to avoid unnecessary computations,
namely getRight() and getBottom().
• These methods return the coordinates of the
right and bottom edges of the rectangle
representing the view.
• For instance, calling getRight() is similar to the
following computation: getLeft() + getWidth().
74Vibrant Technology & Computers
• Size, Padding and Margins
• The size of a view is expressed with a width and a
height.
• A view actually possess two pairs of width and height
values.
• The first pair is known as measured width and
measured height.
• These dimensions define how big a view wants to be
within its parent.
• The measured dimensions can be obtained by calling
getMeasuredWidth() and getMeasuredHeight().
75Vibrant Technology & Computers
• The second pair is simply known as width and
height, or sometimes drawing width and drawing
height.
• These dimensions define the actual size of the
view on screen, at drawing time and after layout.
• These values may, but do not have to, be
different from the measured width and height.
• The width and height can be obtained by calling
getWidth() and getHeight().
76Vibrant Technology & Computers
• To measure its dimensions, a view takes into
account its padding.
• The padding is expressed in pixels for the left,
top, right and bottom parts of the view.
• Padding can be used to offset the content of
the view by a specific amount of pixels.
77Vibrant Technology & Computers
• For instance, a left padding of 2 will push the
view's content by 2 pixels to the right of the
left edge.
• Padding can be set using the setPadding(int,
int, int, int) method and queried by calling
getPaddingLeft(), getPaddingTop(),
getPaddingRight() and getPaddingBottom().
78Vibrant Technology & Computers
• Even though a view can define a padding, it
does not provide any support for margins.
• However, view groups provide such a support.
Refer to ViewGroup and
ViewGroup.MarginLayoutParams for further
information.
• For more information about dimensions, see
Dimension Values.
79Vibrant Technology & Computers
• [Remember that in the graphical development
environment you can set properties.
• For the time being, you can think of the
information given above as general
background on properties.
• As noted a little while back, we hope to avoid
details like this as much as possible.]
80Vibrant Technology & Computers
• Common Layouts
• Each subclass of the ViewGroup class provides
a unique way to display the views you nest
within it.
• Below are some of the more common layout
types that are built into the Android platform.
81Vibrant Technology & Computers
• Linear Layout, Relative Layout, and Web View
82Vibrant Technology & Computers
• Linear Layout
• A layout that organizes its children into a
single horizontal or vertical row.
• It creates a scrollbar if the length of the
window exceeds the length of the screen.
83Vibrant Technology & Computers
• Relative Layout
• Enables you to specify the location of child
objects relative to each other (child A to the
left of child B) or to the parent (aligned to the
top of the parent).
• Web View
• Displays web pages.
84Vibrant Technology & Computers
• Building Layouts with an Adapter
• When the content for your layout is dynamic
or not pre-determined, you can use a layout
that subclasses AdapterView to populate the
layout with views at runtime.
• A subclass of the AdapterView class uses an
Adapter to bind data to its layout.
85Vibrant Technology & Computers
• The Adapter behaves as a middle-man
between the data source and the
AdapterView layout—the Adapter 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.
86Vibrant Technology & Computers
• [This comes up in design patterns—and exists in
the Java API.
• Setting aside Android for the moment:
• Suppose you have an array of objects of the same
class, which each have some string value.
• Suppose your application contains a Table class,
where this class has had its cells defined
generically so they can be populated with
“anything”.
87Vibrant Technology & Computers
• Adaptation has to do with the process of
converting the set of string instance variable
values coming from the array of objects into a
set of objects/values which can populate the
cells in a row of the table.
• The same idea applies when trying to
populate the elements of a ViewGroup which
contains a well defined set of child Views.]
88Vibrant Technology & Computers
• Common layouts backed by an adapter
include: List View, Grid View
89Vibrant Technology & Computers
• List View:
• Displays a scrolling single column list.
• Grid View:
• Displays a scrolling grid of columns and rows.
90Vibrant Technology & Computers
• Filling an adapter view with data
• You can populate an AdapterView such as
ListView or GridView by binding the AdapterView
instance to an Adapter, which retrieves data from
an external source and creates a View that
represents each data entry.
• Android provides several subclasses of Adapter
that are useful for retrieving different kinds of
data and building views for an AdapterView. The
two most common adapters are: [ArrayAdapter,
SimpleCursorAdapter]
91Vibrant Technology & Computers
• ArrayAdapter
• Use this adapter when your data source is an
array.
• By default, ArrayAdapter creates a view for each
array item by calling toString() on each item and
placing the contents in a TextView.
• [Notice our friend toString() doing the conversion
or adaptation of an object and turning it into a
child TextView in an AdapterView.]
92Vibrant Technology & Computers
• 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);
93Vibrant Technology & Computers
• The arguments for this constructor are:
• Your app Context
• The layout that contains a TextView for each
string in the array
• The string array
94Vibrant Technology & Computers
• Then simply call setAdapter() on your
ListView:
• ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
• [Recall the statements made earlier:
• You populate the AdapterView (simply) by
binding it to the adapter (which adapts some
data set).]
95Vibrant Technology & Computers
• To customize the appearance of each item you
can override the toString() method for the
objects in your array.
• Or, to create a view for each item that's
something other than a TextView (for
example, if you want an ImageView for each
array item), extend the ArrayAdapter class and
override getView() to return the type of view
you want for each item.
96Vibrant Technology & Computers
• [There is nothing cosmic about this comment.
• It just gets hard to see the forest for the trees
sometimes.
• All of the preceding information tells you this:
• The whole mechanism is set up by default to
display strings.
• A vanilla ListView consists of a bunch of
TextViews.]
97Vibrant Technology & Computers
• [The next subsection on the CursorAdapter is
included for completeness’ sake.
• But I have no intention of covering it in detail.
• That would require delving into
cursors…which haven’t been covered yet.
• Until we’ve covered more stuff on input
functions, adapting to cursors is off topic.]
98Vibrant Technology & Computers
• SimpleCursorAdapter
• Use this adapter when your data comes from a Cursor.
• 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.
• 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.
99Vibrant Technology & Computers
• 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:
• String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
100Vibrant Technology & Computers
• 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);
101Vibrant Technology & Computers
• The SimpleCursorAdapter then creates a view for
each row in the Cursor using the provided layout
by inserting each fromColumns item into the
corresponding toViews view.
• If, during the course of your application's life, you
change the underlying data that is read by your
adapter, you should call notifyDataSetChanged().
This will notify the attached view that the data
has been changed and it should refresh itself.
102Vibrant Technology & Computers
• [The next section is kind of out of the blue.
• Like the foregoing, it’s included for
completeness’ sake.
• Here is a scenario:
• Suppose you wanted to populate a ListView
with buttons instead of text…
103Vibrant Technology & Computers
• Keep in mind that this section on adaptation
presupposes that you couldn’t completely define
a layout in advance.
• The buttons aren’t there and you can’t predefine
sendMessage() methods for them.
• You’re doing it “programmatically,” namely, when
your Java code is running.
• So at run time, you want to make some buttons
and you’d like them to have functionality.]
104Vibrant Technology & Computers
• 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);
105Vibrant Technology & Computers
• [Notice that the foregoing example code used
the syntax for an anonymous listener.
• The event handling method in the listener is
onItemClick().
• In the coming sections, the use of listeners in
Android Java code will be covered in more
detail.]
106Vibrant Technology & Computers
8.4 Linear Layout
107Vibrant Technology & Computers
• Linear Layout
• LinearLayout is a view group that aligns all
children in a single direction, vertically or
horizontally.
• You can specify the layout direction with the
android:orientation attribute.
108Vibrant Technology & Computers
• All children of a LinearLayout are stacked one
after the other, so a vertical list will only have
one child per row, no matter how wide they
are, and a horizontal list will only be one row
high (the height of the tallest child, plus
padding).
• A LinearLayout respects margins between
children and the gravity (right, center, or left
alignment) of each child.
109Vibrant Technology & Computers
• Layout Weight
• LinearLayout also supports assigning a weight
to individual children with the
android:layout_weight attribute.
• This attribute assigns an "importance" value
to a view in terms of how much space is
should occupy on the screen.
• A larger weight value allows it to expand to fill
any remaining space in the parent view.
110Vibrant Technology & Computers
• Child views can specify a weight value, and
then any remaining space in the view group is
assigned to children in the proportion of their
declared weight.
• Default weight is zero.
111Vibrant Technology & Computers
• For example, if there are three text fields and
two of them declare a weight of 1, while the
other is given no weight, the third text field
without weight will not grow and will only
occupy the area required by its content.
• The other two will expand equally to fill the
space remaining after all three fields are
measured.
112Vibrant Technology & Computers
• If the third field is then given a weight of 2
(instead of 0), then it is now declared more
important than both the others, so it gets half
the total remaining space, while the first two
share the rest equally.
113Vibrant Technology & Computers
• Equally weighted 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".
114Vibrant Technology & Computers
Relative Layout
115Vibrant Technology & Computers
• Relative Layout
• RelativeLayout is a view group that displays
child views in relative positions.
• The position of each view can be specified as
relative to sibling elements (such as to the
left-of or below another view) or in positions
relative to the parent RelativeLayout area
(such as aligned to the bottom, left of center).
116Vibrant Technology & Computers
• A RelativeLayout is a very powerful utility for
designing a user interface because 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.
117Vibrant Technology & Computers
• Positioning Views
• RelativeLayout lets child views specify their
position relative to the parent view or to each
other (specified by ID).
• So you can align two elements by right border, or
make one below another, centered in the screen,
centered left, and so on.
• By default, all child views are drawn at the top-
left of the layout, so you must define the position
of each view using the various layout properties
available from RelativeLayout.LayoutParams.
118Vibrant Technology & Computers
• Some of the many layout properties available
to views in a RelativeLayout include:
• 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.
119Vibrant Technology & Computers
• 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.
• These are just a few examples.
• All layout attributes are documented at
RelativeLayout.LayoutParams.
120Vibrant Technology & Computers
• 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.
• In your XML layout, dependencies against other views
in the layout can be declared in any order. For example,
you can declare that "view1" be positioned below
"view2" even if "view2" is the last view declared in the
hierarchy.
• The example below demonstrates such a scenario.
121Vibrant Technology & Computers
• Example
122Vibrant Technology & Computers
• Each of the attributes that control the relative
position of each view are emphasized.
• [Note that this layout contains spinners.
• They haven’t been introduced yet, but they
will be in the next unit.]
123Vibrant Technology & Computers
• For details about all the layout attributes
available to each child view of a
RelativeLayout, see
RelativeLayout.LayoutParams.
124Vibrant Technology & Computers
List View
125Vibrant Technology & Computers
• List View
• ListView is a view group that displays a list of
scrollable items.
• The list items are automatically inserted to the
list using an Adapter that 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.
• For an introduction to how you can dynamically
insert views using an adapter, read Building
Layouts with an Adapter.
126Vibrant Technology & Computers
127Vibrant Technology & Computers
• Using a Loader
• Using a CursorLoader is the standard way to
query a Cursor as an asynchronous task in order
to avoid blocking your app's main thread with the
query.
• When the CursorLoader receives the Cursor
result, the LoaderCallbacks receives a callback to
onLoadFinished(), which is where you update
your Adapter with the new Cursor and the list
view then displays the results.
128Vibrant Technology & Computers
• Although the CursorLoader APIs were first
introduced in Android 3.0 (API level 11), they
are also available in the Support Library so
that your app may use them while supporting
devices running Android 1.6 or higher.
• For more information about using a Loader to
asynchronously load data, see the Loaders
guide.
129Vibrant Technology & Computers
• 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.
• The activity implements the LoaderCallbacks
interface in order to use a CursorLoader that
dynamically loads the data for the list view.
130Vibrant Technology & Computers
• [Note that this is a lot of information.
• It would take some serious code reading to
figure out what’s going on.
• I probably won’t do this in class.
• It’s here for reference.]
131Vibrant Technology & Computers
• [If you’re interested, this is the kind of thing you
figure out as part of the assignment
• Or you could do this as part of your project.
• Note that one of the uses is in displaying the
results of db queries.
• By definition, you can’t say in advance how many
rows you’ll get.
• So this idea of being able to generate layout
contents programmatically is useful in advanced
settings.]
132Vibrant Technology & Computers
Grid View
133Vibrant Technology & Computers
• Grid View
• GridView is a ViewGroup that displays items in
a two-dimensional, scrollable grid.
• The grid items are automatically inserted to
the layout using a ListAdapter.
• For an introduction to how you can
dynamically insert views using an adapter,
read Building Layouts with an Adapter.
134Vibrant Technology & Computers
135Vibrant Technology & Computers
• Example
• In this tutorial, you'll create a grid of image
thumbnails.
• When an item is selected, a toast message will
display the position of the image.
136Vibrant Technology & Computers
• [Because of the order that I’m presenting things
in, the term Toast hasn’t been explained yet.
• This is from the API.
• “A toast is a view containing a quick little message
for the user.”
• In Java we saw the use of dialog boxes
• A toast isn’t even that complex, but the idea of a
simple, system supplied thing for supporting
interaction with the user is similar.]
137Vibrant Technology & Computers
• 1. Start a new project named HelloGridView.
• 2. Find some photos you'd like to use, or
download these sample images.
• Save the image files into the project's
res/drawable/ directory.
138Vibrant Technology & Computers
• 3. Open the res/layout/main.xml file and insert the following:
•
• <?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk
/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
139Vibrant Technology & Computers
• This GridView will fill the entire screen.
• The attributes are rather self explanatory.
• [?]
• For more information about valid attributes,
see the GridView reference.
140Vibrant Technology & Computers
• 4. Open HelloGridView.java and insert the following
code for the onCreate() method:
• public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int
position, long id) {
Toast.makeText(HelloGridView.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
141Vibrant Technology & Computers
• After the main.xml layout is set for the
content view, the GridView is captured from
the layout with findViewById(int).
• The setAdapter() method then sets a custom
adapter (ImageAdapter) as the source for all
items to be displayed in the grid.
• The ImageAdapter is created in the next step.
142Vibrant Technology & Computers
• To do something when an item in the grid is
clicked, the setOnItemClickListener() method is
passed a new AdapterView.OnItemClickListener.
• This anonymous instance defines the
onItemClick() callback method to show a Toast
that displays the index position (zero-based) of
the selected item (in a real world scenario, the
position could be used to get the full sized image
for some other task).
143Vibrant Technology & Computers
• 5. Create a new class called ImageAdapter that extends
BaseAdapter:
• public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
Run the Application
144Vibrant Technology & Computers
• // create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
145Vibrant Technology & Computers
• // references to our images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}
146Vibrant Technology & Computers
• First, this implements some required methods
inherited from BaseAdapter.
• The constructor and getCount() are self-
explanatory.
• Normally, getItem(int) should return the
actual object at the specified position in the
adapter, but it's ignored for this example.
• Likewise, getItemId(int) should return the row
id of the item, but it's not needed here.
147Vibrant Technology & Computers
• The first method necessary is getView().
• This method creates a new View for each image
added to the ImageAdapter.
• When this is called, a View is passed in, which is
normally a recycled object (at least after this has
been called once), so there's a check to see if the
object is null.
• If it is null, an ImageView is instantiated and
configured with desired properties for the image
presentation:
148Vibrant Technology & Computers
• setLayoutParams(ViewGroup.LayoutParams) sets the
height and width for the View—this ensures that, no
matter the size of the drawable, each image is resized
and cropped to fit in these dimensions, as appropriate.
• setScaleType(ImageView.ScaleType) declares that
images should be cropped toward the center (if
necessary).
• setPadding(int, int, int, int) defines the padding for all
sides. (Note that, if the images have different aspect-
ratios, then less padding will cause more cropping of
the image if it does not match the dimensions given to
the ImageView.)
149Vibrant Technology & Computers
• If the View passed to getView() is not null, then
the local ImageView is initialized with the
recycled View object.
• At the end of the getView() method, the position
integer passed into the method is used to select
an image from the mThumbIds array, which is set
as the image resource for the ImageView.
• All that's left is to define the mThumbIds array of
drawable resources.
150Vibrant Technology & Computers
Thank you…
151Vibrant Technology & Computers

More Related Content

Similar to Android layouts course-in-mumbai

Android ui layout
Android ui layoutAndroid ui layout
Android ui layout
Krazy Koder
 
Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
ZendCon
 
Extending Zend_Tool
Extending Zend_ToolExtending Zend_Tool
Extending Zend_Tool
Ralph Schindler
 
Androidify workshop
Androidify workshopAndroidify workshop
Androidify workshop
Alexey Buzdin
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
Muhammad Sajid
 
Android Screen Containers & Layouts
Android Screen Containers & LayoutsAndroid Screen Containers & Layouts
Android Screen Containers & Layouts
Vijay Rastogi
 
Android Studio development model and.pptx
Android Studio development model and.pptxAndroid Studio development model and.pptx
Android Studio development model and.pptx
VaibhavKhunger2
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
NicheTech Com. Solutions Pvt. Ltd.
 
Consistent UI Across Android Devices
Consistent UI Across Android DevicesConsistent UI Across Android Devices
Consistent UI Across Android Devices
Irene Duke
 
Developing for Android-Types of Android Application
Developing for Android-Types of Android ApplicationDeveloping for Android-Types of Android Application
Developing for Android-Types of Android Application
Nandini Prabhu
 
Bn1 1020 demo android
Bn1 1020 demo  androidBn1 1020 demo  android
Bn1 1020 demo android
conline training
 
Aura Framework Overview
Aura Framework OverviewAura Framework Overview
Aura Framework Overview
rajdeep
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
Brian Ward
 
Ui 5
Ui   5Ui   5
Dojo and Zend Framework
Dojo and Zend  FrameworkDojo and Zend  Framework
Dojo and Zend Framework
Kuldeep Singh
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesInnovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best Practices
Solstice Mobile Argentina
 
Ng Sydney Dynamic Templates Talk - 18 April 2018
Ng Sydney Dynamic Templates Talk - 18 April 2018Ng Sydney Dynamic Templates Talk - 18 April 2018
Ng Sydney Dynamic Templates Talk - 18 April 2018
Roger Kermode
 
Fire up your mobile app!
Fire up your mobile app!Fire up your mobile app!
Fire up your mobile app!
Suganthi Giridharan
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
NETFest
 
Inline Template Puppet Type
Inline Template Puppet TypeInline Template Puppet Type
Inline Template Puppet Type
Lyndon Swan
 

Similar to Android layouts course-in-mumbai (20)

Android ui layout
Android ui layoutAndroid ui layout
Android ui layout
 
Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
 
Extending Zend_Tool
Extending Zend_ToolExtending Zend_Tool
Extending Zend_Tool
 
Androidify workshop
Androidify workshopAndroidify workshop
Androidify workshop
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Android Screen Containers & Layouts
Android Screen Containers & LayoutsAndroid Screen Containers & Layouts
Android Screen Containers & Layouts
 
Android Studio development model and.pptx
Android Studio development model and.pptxAndroid Studio development model and.pptx
Android Studio development model and.pptx
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
 
Consistent UI Across Android Devices
Consistent UI Across Android DevicesConsistent UI Across Android Devices
Consistent UI Across Android Devices
 
Developing for Android-Types of Android Application
Developing for Android-Types of Android ApplicationDeveloping for Android-Types of Android Application
Developing for Android-Types of Android Application
 
Bn1 1020 demo android
Bn1 1020 demo  androidBn1 1020 demo  android
Bn1 1020 demo android
 
Aura Framework Overview
Aura Framework OverviewAura Framework Overview
Aura Framework Overview
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
 
Ui 5
Ui   5Ui   5
Ui 5
 
Dojo and Zend Framework
Dojo and Zend  FrameworkDojo and Zend  Framework
Dojo and Zend Framework
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesInnovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best Practices
 
Ng Sydney Dynamic Templates Talk - 18 April 2018
Ng Sydney Dynamic Templates Talk - 18 April 2018Ng Sydney Dynamic Templates Talk - 18 April 2018
Ng Sydney Dynamic Templates Talk - 18 April 2018
 
Fire up your mobile app!
Fire up your mobile app!Fire up your mobile app!
Fire up your mobile app!
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
 
Inline Template Puppet Type
Inline Template Puppet TypeInline Template Puppet Type
Inline Template Puppet Type
 

Recently uploaded

"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 

Recently uploaded (20)

"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Artificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic WarfareArtificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic Warfare
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 

Android layouts course-in-mumbai

  • 1. Welcome to vibrant technologies and computers. 1Vibrant Technology & Computers
  • 3. Content • These are the sections in this unit: • Introduction • Layouts (Taken from Resources Section of Tutorials) • Layouts (Taken from Layouts Section of Tutorials) • Linear Layout • Relative Layout • List View • Grid View 3Vibrant Technology & Computers
  • 5. • As usual, the decision to present this material at this point is based partially on background ideas found in the book • The contents of the overheads consist largely of material taken from the online tutorials, with occasional commentary by me • The commentary will either be introduced as commentary or appear in square brackets • If not set off in this way, the content is taken from the tutorials 5Vibrant Technology & Computers
  • 6. • As mentioned before, what you’re getting is an idiosyncratic path through some of the various topics covered in the tutorials • The goal is to cover enough of the items involved in sufficient depth so that the perceptive learner could pick up more when needed 6Vibrant Technology & Computers
  • 7. Layouts (Taken from Resources Section of Tutorials) 7Vibrant Technology & Computers
  • 8. • Layout Resource • A layout resource defines the architecture for the UI in an Activity or a component of a UI. • file location: • res/layout/filename.xml • The filename will be used as the resource ID. • compiled resource datatype: • Resource pointer to a View (or subclass) resource. • resource reference: • In Java: R.layout.filename • In XML: @[package:]layout/filename 8Vibrant Technology & Computers
  • 9. • Note: • The root element can be either a ViewGroup, a View, or a <merge> element, but there must be only one root element and it must contain the xmlns:android attribute with the android namespace as shown. 9Vibrant Technology & Computers
  • 10. • elements: • <ViewGroup> • A container for other View elements. • There are many different kinds of ViewGroup objects and each one lets you specify the layout of the child elements in different ways. • Different kinds of ViewGroup objects include LinearLayout, RelativeLayout, and FrameLayout. • You should not assume that any derivation of ViewGroup will accept nested Views. 10Vibrant Technology & Computers
  • 11. • Some ViewGroups are implementations of the AdapterView class, which determines its children only from an Adapter. • [This is not the same as an adapter class in the Java API. • It has more in common with the adapter design pattern of CSCE 202. • More information will be given later in this unit.] 11Vibrant Technology & Computers
  • 12. • attributes: • android:id • Resource ID. • A unique resource name for the element, which you can use to obtain a reference to the ViewGroup from your application. • See more about the value for android:id below. 12Vibrant Technology & Computers
  • 13. • android:layout_height • Dimension or keyword. Required. • The height for the group, as a dimension value (or dimension resource) or a keyword ("fill_parent" or "wrap_content"). • See the valid values below. 13Vibrant Technology & Computers
  • 14. • android:layout_width • Dimension or keyword. Required. • The width for the group, as a dimension value (or dimension resource) or a keyword ("fill_parent" or "wrap_content"). • See the valid values below. 14Vibrant Technology & Computers
  • 15. • More attributes are supported by the ViewGroup base class, and many more are supported by each implementation of ViewGroup. • For a reference of all available attributes, see the corresponding reference documentation for the ViewGroup class (for example, the LinearLayout XML attributes). 15Vibrant Technology & Computers
  • 16. • <View> • An individual UI component, generally referred to as a "widget". • Different kinds of View objects include TextView, Button, and CheckBox. • attributes: • android:id • Resource ID. • A unique resource name for the element, which you can use to obtain a reference to the View from your application. • See more about the value for android:id below. 16Vibrant Technology & Computers
  • 17. • android:layout_height • Dimension or keyword. Required. • The height for the element, as a dimension value (or dimension resource) or a keyword ("fill_parent" or "wrap_content"). • See the valid values below. 17Vibrant Technology & Computers
  • 18. • android:layout_width • Dimension or keyword. Required. • The width for the element, as a dimension value (or dimension resource) or a keyword ("fill_parent" or "wrap_content"). • See the valid values below. 18Vibrant Technology & Computers
  • 19. • More attributes are supported by the View base class, and many more are supported by each implementation of View. • Read Layouts for more information. • For a reference of all available attributes, see the corresponding reference documentation (for example, the TextView XML attributes). 19Vibrant Technology & Computers
  • 20. • <requestFocus> • Any element representing a View object can include this empty element, which gives its parent initial focus on the screen. • You can have only one of these elements per file. 20Vibrant Technology & Computers
  • 21. • <include> • Includes a layout file into this layout. • attributes: • layout • Layout resource. Required. • Reference to a layout resource. 21Vibrant Technology & Computers
  • 22. • android:id • Resource ID. • Overrides the ID given to the root view in the included layout. • android:layout_height • Dimension or keyword. • Overrides the height given to the root view in the included layout. • Only effective if android:layout_width is also declared. 22Vibrant Technology & Computers
  • 23. • android:layout_width • Dimension or keyword. • Overrides the width given to the root view in the included layout. • Only effective if android:layout_height is also declared. • You can include any other layout attributes in the <include> that are supported by the root element in the included layout and they will override those defined in the root element. 23Vibrant Technology & Computers
  • 24. • Caution: • If you want to override layout attributes using the <include> tag, you must override both android:layout_height and android:layout_width in order for other layout attributes to take effect. 24Vibrant Technology & Computers
  • 25. • Another way to include a layout is to use ViewStub. • It is a lightweight View that consumes no layout space until you explicitly inflate it, at which point, it includes a layout file defined by its android:layout attribute. • For more information about using ViewStub, read Loading Views On Demand. 25Vibrant Technology & Computers
  • 26. • <merge> • An alternative root element that is not drawn in the layout hierarchy. • Using this as the root element is useful when you know that this layout will be placed into a layout that already contains the appropriate parent View to contain the children of the <merge> element. • This is particularly useful when you plan to include this layout in another layout file using <include> and this layout doesn't require a different ViewGroup container. • For more information about merging layouts, read Re- using Layouts with <include/>. 26Vibrant Technology & Computers
  • 27. • Value for android:id • For the ID value, you should usually use this syntax form: "@+id/name". • The plus symbol, +, indicates that this is a new resource ID and the aapt tool will create a new resource integer in the R.java class, if it doesn't already exist. For example: • <TextView android:id="@+id/nameTextbox"/> 27Vibrant Technology & Computers
  • 28. • The nameTextbox name is now a resource ID attached to this element. • You can then refer to the TextView to which the ID is associated in Java: • findViewById(R.id.nameTextbox); • This code returns the TextView object. • However, if you have already defined an ID resource (and it is not already used), then you can apply that ID to a View element by excluding the plus symbol in the android:id value. 28Vibrant Technology & Computers
  • 29. • Value for android:layout_height and android:layout_width: • The height and width value can be expressed using any of the dimension units supported by Android (px, dp, sp, pt, in, mm) or with the following keywords: 29Vibrant Technology & Computers
  • 30. Value Description match_parent Sets the dimension to match that of the parent element. Added in API Level 8 to deprecate fill_parent. fill_parent Sets the dimension to match that of the parent element. wrap_content Sets the dimension only to the size required to fit the content of this element. 30Vibrant Technology & Computers
  • 31. • Custom View elements • You can create your own custom View and ViewGroup elements and apply them to your layout the same as a standard layout element. • You can also specify the attributes supported in the XML element. • To learn more, see the Custom Components developer guide. 31Vibrant Technology & Computers
  • 32. • example: • XML file saved at res/layout/main_activity.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/androi d" 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> 32Vibrant Technology & Computers
  • 33. • This application code will load the layout for an Activity, in the onCreate() method: • public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); } • [Read it again for the second time… • The point is that the onCreate() method starts with a setContentView() call. • This is what connects a Java app file to its layout file.] 33Vibrant Technology & Computers
  • 34. 8.3 Layouts (Taken from Layouts Section of Tutorials) 34Vibrant Technology & Computers
  • 35. • Layouts • A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. • You can declare a layout in two ways: • [1] Declare UI elements in XML. • Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. 35Vibrant Technology & Computers
  • 36. • [2] Instantiate layout elements at runtime. • Your application can create View and ViewGroup objects (and manipulate their properties) programmatically. 36Vibrant Technology & Computers
  • 37. • The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application's UI. • For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. • You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time. 37Vibrant Technology & Computers
  • 38. • 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. • Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. 38Vibrant Technology & Computers
  • 39. • For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. • Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. • As such, this document focuses on teaching you how to declare your layout in XML. 39Vibrant Technology & Computers
  • 40. • If you're interested in instantiating View objects at runtime, refer to the ViewGroup and View class references. 40Vibrant Technology & Computers
  • 41. • In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. • In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. 41Vibrant Technology & Computers
  • 42. • However, note that not all vocabulary is identical. • In some cases, there are slight naming differences. 42Vibrant Technology & Computers
  • 43. • For example, the EditText element has a text attribute that corresponds to EditText.setText(). • [They got their explanations slightly out of order. • The text attribute and setText() method are an example of correspondence. • The are not intended as an example of a case with a slight difference.] 43Vibrant Technology & Computers
  • 44. • Tip: • Learn more about different layout types in Common Layout Objects. • There are also a collection of tutorials on building various layouts in the Hello Views tutorial guide. 44Vibrant Technology & Computers
  • 45. • Write the XML • Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements. • Each layout file must contain exactly one root element, which must be a View or ViewGroup object. 45Vibrant Technology & Computers
  • 46. • Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. • For example, here's an XML layout that uses a vertical LinearLayout to hold a TextView and a Button: 46Vibrant Technology & Computers
  • 47. • <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/androi d" 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> 47Vibrant Technology & Computers
  • 48. • After you've declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile. • More information about the syntax for a layout XML file is available in the Layout Resources document. 48Vibrant Technology & Computers
  • 49. • Load the XML Resource • When you compile your application, each XML layout file is compiled into a View resource. • You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. 49Vibrant Technology & Computers
  • 50. • Do so by calling setContentView(), passing it the reference to your layout resource in the form of: • R.layout.layout_file_name • For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so: 50Vibrant Technology & Computers
  • 51. • public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); } • The onCreate() callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the Activities document). 51Vibrant Technology & Computers
  • 52. • [It may be worth noting something here: • You can access layouts directly using their name as given in R.java: • setContentView(R.layout.main_layout); • Contrast this with how you acquire a reference to an individual view in a layout: • EditText myEditText = (EditText) findViewById(R.id.input_message_view); 52Vibrant Technology & Computers
  • 53. • Or how you access a resource: • Resources res = getResources(); • String[] prompts = res.getStringArray(R.array.prompt_array); • int colorIndex = res.getInteger(R.integer.numberInColorCycle); • ] 53Vibrant Technology & Computers
  • 54. • Attributes • Every View and ViewGroup object supports their own variety of XML attributes. • Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. 54Vibrant Technology & Computers
  • 55. • Some are common to all View objects, because they are inherited from the root View class (like the id attribute). • And, other attributes are considered "layout parameters," which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object. 55Vibrant Technology & Computers
  • 56. • ID • Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. • When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. 56Vibrant Technology & Computers
  • 57. • This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. • The syntax for an ID, inside an XML tag is: • android:id="@+id/my_button" 57Vibrant Technology & Computers
  • 58. • The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. • The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). 58Vibrant Technology & Computers
  • 59. • There are a number of other ID resources that are offered by the Android framework. • When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so: • android:id="@android:id/empty" 59Vibrant Technology & Computers
  • 60. • With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class. • [If accurate, this is an interesting statement. • We’re being told something about the meaning of the syntax. • Java app code depends on R.java. • After the related project files are built, layout and other resource files also depend on R.java for id’s.] 60Vibrant Technology & Computers
  • 61. • In order to create views and reference them from the application, a common pattern is to: • 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"/> 61Vibrant Technology & Computers
  • 62. • 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); • [You’re not creating an instance of the object. • You’re recovering a reference to the object as defined/created in the layout file.] 62Vibrant Technology & Computers
  • 63. • Defining IDs for view objects is important when creating a RelativeLayout. • In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID. 63Vibrant Technology & Computers
  • 64. • An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible). • [Clowns: Just make them globally unique.] 64Vibrant Technology & Computers
  • 65. • Layout Parameters • XML layout attributes named layout_something define 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 property types that define the size and position for each child view, as appropriate for the view group. 65Vibrant Technology & Computers
  • 66. • As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group). • [Following overhead] • [General note on this topic: • What they seem to be saying is that a parent in effect defines what kinds of parameters its children will have. • It’s up to the children to use values which are appropriate to the parameters defined in their parents.] 66Vibrant Technology & Computers
  • 67. Figure 1. Visualization of a view hierarchy with layout parameters associated with each view. 67Vibrant Technology & Computers
  • 68. • Note that every LayoutParams subclass has its own syntax for setting values. • Each child element must define LayoutParams that are appropriate for its parent, though it may also define different LayoutParams for its own children. • All view groups include a width and height (layout_width and layout_height), and each view is required to define them. • Many LayoutParams also include optional margins and borders. 68Vibrant Technology & Computers
  • 69. • You can specify width and height with exact measurements, though you probably won't want to do this often. • More often, you will use one of these constants to set the width or height: • 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. 69Vibrant Technology & Computers
  • 70. • In general, specifying a layout width and height using absolute units such as pixels is not recommended. • Instead, using relative measurements such as density-independent pixel units (dp), wrap_content, or fill_parent, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes. • The accepted measurement types are defined in the Available Resources document. 70Vibrant Technology & Computers
  • 71. • Layout Position • The geometry of a view is that of a rectangle. • A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. • The unit for location and dimensions is the pixel. 71Vibrant Technology & Computers
  • 72. • It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). • The former returns the left, or X, coordinate of the rectangle representing the view. • The latter returns the top, or Y, coordinate of the rectangle representing the view. • [Notice the similarity with the bounding box in Java graphics.] 72Vibrant Technology & Computers
  • 73. • These methods both return the location of the view relative to its parent. • For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent. • [Keep in mind that this is of pretty remote usefulness. • In general we’d like to avoid hardcoding dimensional values.] 73Vibrant Technology & Computers
  • 74. • In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). • These methods return the coordinates of the right and bottom edges of the rectangle representing the view. • For instance, calling getRight() is similar to the following computation: getLeft() + getWidth(). 74Vibrant Technology & Computers
  • 75. • Size, Padding and Margins • The size of a view is expressed with a width and a height. • A view actually possess two pairs of width and height values. • The first pair is known as measured width and measured height. • These dimensions define how big a view wants to be within its parent. • The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight(). 75Vibrant Technology & Computers
  • 76. • The second pair is simply known as width and height, or sometimes drawing width and drawing height. • These dimensions define the actual size of the view on screen, at drawing time and after layout. • These values may, but do not have to, be different from the measured width and height. • The width and height can be obtained by calling getWidth() and getHeight(). 76Vibrant Technology & Computers
  • 77. • To measure its dimensions, a view takes into account its padding. • The padding is expressed in pixels for the left, top, right and bottom parts of the view. • Padding can be used to offset the content of the view by a specific amount of pixels. 77Vibrant Technology & Computers
  • 78. • For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. • Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom(). 78Vibrant Technology & Computers
  • 79. • Even though a view can define a padding, it does not provide any support for margins. • However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information. • For more information about dimensions, see Dimension Values. 79Vibrant Technology & Computers
  • 80. • [Remember that in the graphical development environment you can set properties. • For the time being, you can think of the information given above as general background on properties. • As noted a little while back, we hope to avoid details like this as much as possible.] 80Vibrant Technology & Computers
  • 81. • Common Layouts • Each subclass of the ViewGroup class provides a unique way to display the views you nest within it. • Below are some of the more common layout types that are built into the Android platform. 81Vibrant Technology & Computers
  • 82. • Linear Layout, Relative Layout, and Web View 82Vibrant Technology & Computers
  • 83. • Linear Layout • A layout that organizes its children into a single horizontal or vertical row. • It creates a scrollbar if the length of the window exceeds the length of the screen. 83Vibrant Technology & Computers
  • 84. • Relative Layout • Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). • Web View • Displays web pages. 84Vibrant Technology & Computers
  • 85. • Building Layouts with an Adapter • When the content for your layout is dynamic or not pre-determined, you can use a layout that subclasses AdapterView to populate the layout with views at runtime. • A subclass of the AdapterView class uses an Adapter to bind data to its layout. 85Vibrant Technology & Computers
  • 86. • The Adapter behaves as a middle-man between the data source and the AdapterView layout—the Adapter 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. 86Vibrant Technology & Computers
  • 87. • [This comes up in design patterns—and exists in the Java API. • Setting aside Android for the moment: • Suppose you have an array of objects of the same class, which each have some string value. • Suppose your application contains a Table class, where this class has had its cells defined generically so they can be populated with “anything”. 87Vibrant Technology & Computers
  • 88. • Adaptation has to do with the process of converting the set of string instance variable values coming from the array of objects into a set of objects/values which can populate the cells in a row of the table. • The same idea applies when trying to populate the elements of a ViewGroup which contains a well defined set of child Views.] 88Vibrant Technology & Computers
  • 89. • Common layouts backed by an adapter include: List View, Grid View 89Vibrant Technology & Computers
  • 90. • List View: • Displays a scrolling single column list. • Grid View: • Displays a scrolling grid of columns and rows. 90Vibrant Technology & Computers
  • 91. • Filling an adapter view with data • You can populate an AdapterView such as ListView or GridView by binding the AdapterView instance to an Adapter, which retrieves data from an external source and creates a View that represents each data entry. • Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView. The two most common adapters are: [ArrayAdapter, SimpleCursorAdapter] 91Vibrant Technology & Computers
  • 92. • ArrayAdapter • Use this adapter when your data source is an array. • By default, ArrayAdapter creates a view for each array item by calling toString() on each item and placing the contents in a TextView. • [Notice our friend toString() doing the conversion or adaptation of an object and turning it into a child TextView in an AdapterView.] 92Vibrant Technology & Computers
  • 93. • 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); 93Vibrant Technology & Computers
  • 94. • The arguments for this constructor are: • Your app Context • The layout that contains a TextView for each string in the array • The string array 94Vibrant Technology & Computers
  • 95. • Then simply call setAdapter() on your ListView: • ListView listView = (ListView) findViewById(R.id.listview); listView.setAdapter(adapter); • [Recall the statements made earlier: • You populate the AdapterView (simply) by binding it to the adapter (which adapts some data set).] 95Vibrant Technology & Computers
  • 96. • To customize the appearance of each item you can override the toString() method for the objects in your array. • Or, to create a view for each item that's something other than a TextView (for example, if you want an ImageView for each array item), extend the ArrayAdapter class and override getView() to return the type of view you want for each item. 96Vibrant Technology & Computers
  • 97. • [There is nothing cosmic about this comment. • It just gets hard to see the forest for the trees sometimes. • All of the preceding information tells you this: • The whole mechanism is set up by default to display strings. • A vanilla ListView consists of a bunch of TextViews.] 97Vibrant Technology & Computers
  • 98. • [The next subsection on the CursorAdapter is included for completeness’ sake. • But I have no intention of covering it in detail. • That would require delving into cursors…which haven’t been covered yet. • Until we’ve covered more stuff on input functions, adapting to cursors is off topic.] 98Vibrant Technology & Computers
  • 99. • SimpleCursorAdapter • Use this adapter when your data comes from a Cursor. • 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. • 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. 99Vibrant Technology & Computers
  • 100. • 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: • String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; int[] toViews = {R.id.display_name, R.id.phone_number}; 100Vibrant Technology & Computers
  • 101. • 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); 101Vibrant Technology & Computers
  • 102. • The SimpleCursorAdapter then creates a view for each row in the Cursor using the provided layout by inserting each fromColumns item into the corresponding toViews view. • If, during the course of your application's life, you change the underlying data that is read by your adapter, you should call notifyDataSetChanged(). This will notify the attached view that the data has been changed and it should refresh itself. 102Vibrant Technology & Computers
  • 103. • [The next section is kind of out of the blue. • Like the foregoing, it’s included for completeness’ sake. • Here is a scenario: • Suppose you wanted to populate a ListView with buttons instead of text… 103Vibrant Technology & Computers
  • 104. • Keep in mind that this section on adaptation presupposes that you couldn’t completely define a layout in advance. • The buttons aren’t there and you can’t predefine sendMessage() methods for them. • You’re doing it “programmatically,” namely, when your Java code is running. • So at run time, you want to make some buttons and you’d like them to have functionality.] 104Vibrant Technology & Computers
  • 105. • 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); 105Vibrant Technology & Computers
  • 106. • [Notice that the foregoing example code used the syntax for an anonymous listener. • The event handling method in the listener is onItemClick(). • In the coming sections, the use of listeners in Android Java code will be covered in more detail.] 106Vibrant Technology & Computers
  • 107. 8.4 Linear Layout 107Vibrant Technology & Computers
  • 108. • Linear Layout • LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. • You can specify the layout direction with the android:orientation attribute. 108Vibrant Technology & Computers
  • 109. • All children of a LinearLayout are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row high (the height of the tallest child, plus padding). • A LinearLayout respects margins between children and the gravity (right, center, or left alignment) of each child. 109Vibrant Technology & Computers
  • 110. • Layout Weight • LinearLayout also supports assigning a weight to individual children with the android:layout_weight attribute. • This attribute assigns an "importance" value to a view in terms of how much space is should occupy on the screen. • A larger weight value allows it to expand to fill any remaining space in the parent view. 110Vibrant Technology & Computers
  • 111. • Child views can specify a weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. • Default weight is zero. 111Vibrant Technology & Computers
  • 112. • For example, if there are three text fields and two of them declare a weight of 1, while the other is given no weight, the third text field without weight will not grow and will only occupy the area required by its content. • The other two will expand equally to fill the space remaining after all three fields are measured. 112Vibrant Technology & Computers
  • 113. • If the third field is then given a weight of 2 (instead of 0), then it is now declared more important than both the others, so it gets half the total remaining space, while the first two share the rest equally. 113Vibrant Technology & Computers
  • 114. • Equally weighted 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". 114Vibrant Technology & Computers
  • 116. • Relative Layout • RelativeLayout is a view group that displays child views in relative positions. • The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left of center). 116Vibrant Technology & Computers
  • 117. • A RelativeLayout is a very powerful utility for designing a user interface because 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. 117Vibrant Technology & Computers
  • 118. • Positioning Views • RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID). • So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on. • By default, all child views are drawn at the top- left of the layout, so you must define the position of each view using the various layout properties available from RelativeLayout.LayoutParams. 118Vibrant Technology & Computers
  • 119. • Some of the many layout properties available to views in a RelativeLayout include: • 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. 119Vibrant Technology & Computers
  • 120. • 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. • These are just a few examples. • All layout attributes are documented at RelativeLayout.LayoutParams. 120Vibrant Technology & Computers
  • 121. • 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. • In your XML layout, dependencies against other views in the layout can be declared in any order. For example, you can declare that "view1" be positioned below "view2" even if "view2" is the last view declared in the hierarchy. • The example below demonstrates such a scenario. 121Vibrant Technology & Computers
  • 123. • Each of the attributes that control the relative position of each view are emphasized. • [Note that this layout contains spinners. • They haven’t been introduced yet, but they will be in the next unit.] 123Vibrant Technology & Computers
  • 124. • For details about all the layout attributes available to each child view of a RelativeLayout, see RelativeLayout.LayoutParams. 124Vibrant Technology & Computers
  • 126. • List View • ListView is a view group that displays a list of scrollable items. • The list items are automatically inserted to the list using an Adapter that 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. • For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter. 126Vibrant Technology & Computers
  • 128. • Using a Loader • Using a CursorLoader is the standard way to query a Cursor as an asynchronous task in order to avoid blocking your app's main thread with the query. • When the CursorLoader receives the Cursor result, the LoaderCallbacks receives a callback to onLoadFinished(), which is where you update your Adapter with the new Cursor and the list view then displays the results. 128Vibrant Technology & Computers
  • 129. • Although the CursorLoader APIs were first introduced in Android 3.0 (API level 11), they are also available in the Support Library so that your app may use them while supporting devices running Android 1.6 or higher. • For more information about using a Loader to asynchronously load data, see the Loaders guide. 129Vibrant Technology & Computers
  • 130. • 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. • The activity implements the LoaderCallbacks interface in order to use a CursorLoader that dynamically loads the data for the list view. 130Vibrant Technology & Computers
  • 131. • [Note that this is a lot of information. • It would take some serious code reading to figure out what’s going on. • I probably won’t do this in class. • It’s here for reference.] 131Vibrant Technology & Computers
  • 132. • [If you’re interested, this is the kind of thing you figure out as part of the assignment • Or you could do this as part of your project. • Note that one of the uses is in displaying the results of db queries. • By definition, you can’t say in advance how many rows you’ll get. • So this idea of being able to generate layout contents programmatically is useful in advanced settings.] 132Vibrant Technology & Computers
  • 134. • Grid View • GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. • The grid items are automatically inserted to the layout using a ListAdapter. • For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter. 134Vibrant Technology & Computers
  • 136. • Example • In this tutorial, you'll create a grid of image thumbnails. • When an item is selected, a toast message will display the position of the image. 136Vibrant Technology & Computers
  • 137. • [Because of the order that I’m presenting things in, the term Toast hasn’t been explained yet. • This is from the API. • “A toast is a view containing a quick little message for the user.” • In Java we saw the use of dialog boxes • A toast isn’t even that complex, but the idea of a simple, system supplied thing for supporting interaction with the user is similar.] 137Vibrant Technology & Computers
  • 138. • 1. Start a new project named HelloGridView. • 2. Find some photos you'd like to use, or download these sample images. • Save the image files into the project's res/drawable/ directory. 138Vibrant Technology & Computers
  • 139. • 3. Open the res/layout/main.xml file and insert the following: • • <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk /res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" /> 139Vibrant Technology & Computers
  • 140. • This GridView will fill the entire screen. • The attributes are rather self explanatory. • [?] • For more information about valid attributes, see the GridView reference. 140Vibrant Technology & Computers
  • 141. • 4. Open HelloGridView.java and insert the following code for the onCreate() method: • public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show(); } }); } 141Vibrant Technology & Computers
  • 142. • After the main.xml layout is set for the content view, the GridView is captured from the layout with findViewById(int). • The setAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. • The ImageAdapter is created in the next step. 142Vibrant Technology & Computers
  • 143. • To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a new AdapterView.OnItemClickListener. • This anonymous instance defines the onItemClick() callback method to show a Toast that displays the index position (zero-based) of the selected item (in a real world scenario, the position could be used to get the full sized image for some other task). 143Vibrant Technology & Computers
  • 144. • 5. Create a new class called ImageAdapter that extends BaseAdapter: • public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } Run the Application 144Vibrant Technology & Computers
  • 145. • // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } 145Vibrant Technology & Computers
  • 146. • // references to our images private Integer[] mThumbIds = { R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 }; } 146Vibrant Technology & Computers
  • 147. • First, this implements some required methods inherited from BaseAdapter. • The constructor and getCount() are self- explanatory. • Normally, getItem(int) should return the actual object at the specified position in the adapter, but it's ignored for this example. • Likewise, getItemId(int) should return the row id of the item, but it's not needed here. 147Vibrant Technology & Computers
  • 148. • The first method necessary is getView(). • This method creates a new View for each image added to the ImageAdapter. • When this is called, a View is passed in, which is normally a recycled object (at least after this has been called once), so there's a check to see if the object is null. • If it is null, an ImageView is instantiated and configured with desired properties for the image presentation: 148Vibrant Technology & Computers
  • 149. • setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View—this ensures that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as appropriate. • setScaleType(ImageView.ScaleType) declares that images should be cropped toward the center (if necessary). • setPadding(int, int, int, int) defines the padding for all sides. (Note that, if the images have different aspect- ratios, then less padding will cause more cropping of the image if it does not match the dimensions given to the ImageView.) 149Vibrant Technology & Computers
  • 150. • If the View passed to getView() is not null, then the local ImageView is initialized with the recycled View object. • At the end of the getView() method, the position integer passed into the method is used to select an image from the mThumbIds array, which is set as the image resource for the ImageView. • All that's left is to define the mThumbIds array of drawable resources. 150Vibrant Technology & Computers