0% found this document useful (0 votes)
135 views33 pages

Android UI Lecture Layout

The document discusses user interfaces and views in Android mobile application development. It describes the View class as the basic building block for user interface components. The View occupies a rectangular area and is responsible for drawing and handling events. It also discusses ViewGroups which are invisible containers that define the composition of child Views and Views. Finally, it provides examples of common UI components like buttons, text fields and layouts.

Uploaded by

Nabby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Topics covered

  • View Class,
  • Java Integration,
  • User Interaction,
  • XML Layout,
  • Resource Management,
  • FrameLayout,
  • Development Environment,
  • Layout Parameters,
  • UI Components,
  • Debugging
0% found this document useful (0 votes)
135 views33 pages

Android UI Lecture Layout

The document discusses user interfaces and views in Android mobile application development. It describes the View class as the basic building block for user interface components. The View occupies a rectangular area and is responsible for drawing and handling events. It also discusses ViewGroups which are invisible containers that define the composition of child Views and Views. Finally, it provides examples of common UI components like buttons, text fields and layouts.

Uploaded by

Nabby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Topics covered

  • View Class,
  • Java Integration,
  • User Interaction,
  • XML Layout,
  • Resource Management,
  • FrameLayout,
  • Development Environment,
  • Layout Parameters,
  • UI Components,
  • Debugging

Mobile Application Development in

Android

Bangladesh-Korea Information Access Center (IAC)


Department of Computer Science and Engineering (CSE)
Bangladesh University of Engineering and Technology (BUET)
USER INTERFACES
The View Class

• View class represents the basic block for user


interface components.
• Each View occupies a rectangular area on the
screen and is responsible for drawing (drawing) and
event handling (event handlers).
• View is the base class for widgets, used to create
the interactive component of the UI (buttons, text
fields, etc.).
• ViewGroup subclass is the base class for all layout
(layout), is the invisible container that contains the
View (or ViewGroup) and other provisions of the
characteristics of their composition.
View

• All of view in a window is organized in a tree


structure.
• We can add the view from the source or definition of
the view tree structure in one or more XML layout
file.

4
After creating a View

• Set properties: for example assign text in a TextView


available. The property that previously could be built
in the XML layout file.
• Set focus: focus mechanism movement in response
to user input. To view requirements for a specific
focus, call requestFocus ().
• Set up listeners: View lets put the listener, the
listener is invoked when an event occurs for the view.
• Button using an event listener to hear the button is
clicked.
• Set visibility: You can hide or show the view by
setVisibility (int).
5
A brief sample of UI components

Linear Layout Relative Layout Table Layout


A LinearLayout is a A RelativeLayout is a ViewGroup A TableLayout is a
GroupView that will lay that allows you to layout child ViewGroup that will lay
child View elements elements in positions relative to child View elements into
vertically or horizontally. the parent or siblings elements. rows and columns.

6
A brief sample of UI components

GalleryView

TabWidget

Spinner

DatePicker Form Controls


A DatePicke is a widget Includes a variety of typical
that allows the user to form widgets, like:
select a month, day and image buttons,
year. text fields,
checkboxes and
radio buttons.
7
A brief sample of UI components

WebView

MapView

AutoCompleteTextView ListView
It is a version of the EditText A ListView is a View that
widget that will provide shows items in a vertically
auto-complete suggestions scrolling list. The items are
as the user types. The acquired from a ListAdapter.
suggestions are extracted
from a collection of strings.
8
What is an XML Layout?

XML-based layout is a specification of the UI components


(widgets), the relationship between them and the container
containing them - all are written in XML format.

Android as the XML-


based layout is the
resource (resource),
and the layout file is
saved in the folder
res/layout of our
project.

9
What is an XML Layout?

• Each XML file contains a hierarchical tree structure,


specification and layout of the container widget
component of a View.
• The properties of each XML element is the nature
and describe the appearance of the widget or the
operation of a container.
• Example:
• If a Button element with an attribute value
android: textStyle = "bold"
This means that the text on the button should be
drawn with bold font (bold).

10
An example

import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AndDemo extends Activity {


Button btn;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.myButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
updateTime();
}
});
}// onCreate
//
private void updateTime() {
btn.setText(new Date().toString());
}

11
An example

This is the XML-Layout definition

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


<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myButton"
android:text=""
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

• The root element (root) to Android XML namespace declarations:


xmlns:android = http://schemas.android.com/apk/res/android
• All other elements are children of the root and will inherit that namespace
declaration.
• Because we want to call it button from within Java code, we need to give
it an id attribute via android: id.
12
An example cont.

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


<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myButton"
android:text=""
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
• The remaining attributes of the entity Button are:
• android:text initial value of the string to the current text on the buttons
(here is the empty string)
• android:layout_width and android:layout_height tell that the width and
height of the buttons occupy the entire container (parent), here is the
entire screen.

13
UI Hierarchy
Look for your SDK folder, usually:
C:/your_sdk_path/android_sdk_windows/tools

UI
Tree

The utility HierarchyViewer displays the UI structure of the current screen


shown on the emulator or device.

( Execute app on emulator, execute HierarchyViewer, click on Emulator >


Refresh Screenshot )
14
Android Layouts

Each element in the XML Layout is either a View or ViewGroup object

15
Android Layouts

• Displaying the Application’s View


– The Android UI Framework paints the screen by walking the View tree
by asking each component to draw itself in a pre-order traversal way.
– Each component draws itself and then asks each of its children to do
the same.

16
Android Layouts

Example: Display UI Hierarchy


Using SDK
older than r8.

vertical

Horizontal 1

Horizontal 2

17
Android Layouts

Example: Display UI Hierarchy

vertical
UI
Tree

Horizontal 1

Horizontal 2

18
Example: Display UI Hierarchy

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


<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<EditText android:id="@+id/txtXcoord" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="X Coord"
android:layout_weight="1">
</EditText>
<EditText android:id="@+id/edtYcoord" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Y Coord"
android:layout_weight="1">
</EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout03"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button android:id="@+id/btnRed" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="red"
android:layout_weight="1">
</Button>
<Button android:id="@+id/btnGreen" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="green"
android:layout_weight="1">
</Button>
See: Android – Application Development, by R. Rogers et al. O’Reilly Pub. 2009, ISBN 978-0-596-52147-0
</LinearLayout>
</LinearLayout> 19
Common Layouts

• There are five basic types of Layouts


– Frame,
– Linear
– Relative
– Table
– Absolute.

20
Common Layouts: FrameLayout

• FrameLayout is the simplest type of layout object.


• It's basically a blank space on your screen that you can later
fill with a single object — for example, a picture that you'll
swap in and out.
• All child elements of the FrameLayout are pinned to the top
left corner of the screen; you cannot specify a different
location for a child view.
• Subsequent child views will simply be drawn over previous
ones, partially or totally obscuring them (unless the newer
object is transparent).

21
Common Layouts: LinearLayout

• LinearLayout aligns all children in a single direction —


vertically or horizontally depending on the
android:orientation attribute.
• All children are stacked one after the other
– vertical list will only have one child per row, no matter how wide they
are
– 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.

22
Common Layouts: LinearLayout
You may attribute a weight to children of a LinearLayout.
Weight gives an "importance" value to a view, and allows it to expand to fill any remaining
space in the parent view.

Example:
The following two forms represent a LinearLayout
with a set of elements: a button, some labels and
text boxes. The text boxes have their width set to
fill_parent; other elements are set to wrap_content.
The gravity, by default, is left.

The difference between the two versions of the


form is that the form on the left has weight values
unset (0 by default), while the form on the right has
the comments text box weight set to 1. If the Name
textbox had also been set to 1, the Name and
Comments text boxes would be the same height.

23
Common Layouts: TableLayout

• TableLayout positions its children into rows and


columns.
• TableLayout containers do not display border lines.
• The table will have as many columns as the row with
the most cells.
• A cell could be empty, but cannot span columns, as
they can in HTML.
• A TableRow object defines a single row in the table.
• A row has zero or more cells, each cell is defined by
any kind of other View.
• A cell may also be a ViewGroup object.

24
Common Layouts: TableLayout

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


TableLayout Example
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
The following sample layout has
android:layout_width="fill_parent" two rows and two cells in each.
android:layout_height="fill_parent" The accompanying screenshot
android:stretchColumns="*"> shows the result, with cell
<TableRow> borders displayed as dotted
<TextView android:text="Open…" lines (added for visual effect).
android:padding="3dip" />
<TextView android:text="Ctrl-O"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView android:text="Save As…"
android:padding="3dip" />
<TextView android:text="Ctrl-Shift-S"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout> 25
Common Layouts: RelativeLayout

• RelativeLayout lets child views specify their position relative


to the parent view or to each other (specified by ID).
• You can align two elements by right border, or make one
below another, centered in the screen, centered left, and so
on.
• Elements are rendered in the order given, so if the first
element is centered in the screen, other elements aligning
themselves to that element will be aligned relative to screen
center.
• Also, because of this ordering, if using XML to specify this
layout, the element that you will reference (in order to
position other view objects) must be listed in the XML file
before you refer to it from the other views via its reference
ID.

26
Common Layouts: RelativeLayout

• The defined RelativeLayout parameters are


(android:layout_...) :

• width, height,
• below, above
• alignTop, alignParentTop,
• alignBottom, alignParentBottom
• toLeftOf, toRightOf

• padding [Bottom|Left|Right|Top], and


• margin [Bottom|Left|Right|Top].

For example, assigning the parameter

android:layout_toLeftOf=“@+id/my_button"
to a TextView would place the TextView to the left of the View with the ID my_button
27
Common Layouts: RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" RelativeLayout Example
android:background="#ff0000ff"
android:padding="10px" >

<TextView android:id="@+id/label"
The example below shows an XML file
android:layout_width="fill_parent" and the resulting screen in the UI. Note
android:layout_height="wrap_content" that the attributes that refer to relative
android:background="#ffff0077" elements (e.g., layout_toLeft) refer to
android:text="Type here:" /> the ID using the syntax of a relative
resource (@+id/id).
<EditText android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/label" />

Continue next page


28
Common Layouts: RelativeLayout

<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
RelativeLayout Example
android:layout_height="wrap_content" Cont.
android:layout_below="@+id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10px"
android:text="OK" />

<Button
android:text="Cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/ok"
android:layout_alignTop="@+id/ok“ />

</RelativeLayout>

29
Common Layouts: AbsoluteLayout

• AbsoluteLayout that lets you specify exact locations (x/y


coordinates) of its children.
• AbsoluteLayouts are less flexible and harder to maintain than
other types of layouts without absolute positioning.
Attaching Layouts to Java Code

Plumbing. We have to 'connect' with parts of objects from XML equivalent


in activity. Thus, we can manipulate the UI from program code.

XLM Layout
<xml….
...
...
</xml>

JAVA code
public class ….
{
...
...
}
31
Attaching Layouts to Java Code

• Suppose UI was created in res / layout / main.xml.


Applications can call this layout with the command
• setContentView(R.layout.main);
• Can access the widget, such myButton, findViewByID
command (...) as follows
• Button btn = (Button)
findViewByID(R.id.myButton);
• In particular, R is an automatically generated class to track
the application's resources. Specifically, R.id. .. the widget is
defined in the XML layout

32
Attaching Layouts to Java Code

• Attach Listener to Widget (event handling)


– Button in your example you can use after you add a listener for the
click event:

btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
updateTime();
}
});

private void updateTime() {


btn.setText(new Date().toString());
}

33

Common questions

Powered by AI

LinearLayout and RelativeLayout serve different purposes in Android UI design. LinearLayout aligns all child elements in a single direction (either vertically or horizontally) based on the 'android:orientation' attribute and is ideal for simple vertical or horizontal arrangements. It respects children’s margins and gravity and can assign weights to children to fill remaining space . Conversely, RelativeLayout allows for positioning child views relative to each other or the parent view, enabling more complex layouts as elements can be aligned based on sibling or parent positions. It's used when relationships among UI components in a layout need to be more dynamic and dependent on each other's presence and dimensions .

XML layout files define the UI components, their relationships, and the containers containing them in a hierarchical tree structure, essential for Android UI design. The files specify both the appearance and behavior of the widgets and are saved in the "res/layout" directory of a project. They enable developers to design complex and nested UI structures declaratively, allowing for a clear separation between UI design and business logic. XML layout files are automatically interpreted by Android to render the UI, forming a crucial part of resource management within the app .

Event handling for button clicks in Android applications is implemented using event listeners. Components like buttons are assigned 'setOnClickListener' methods, wherein the listener interface is implemented to define what actions occur upon user interaction. When a button is clicked, the overridden 'onClick' method is invoked, executing the specified functionality. In Java code, the button listeners are typically established in the 'onCreate' method, linking the user action with application behavior .

XML namespaces in Android's UI framework prevent naming conflicts by uniquely identifying the properties of XML elements related to Android. They are typically declared in the root element of an XML layout file using the 'xmlns:android' attribute, linking to the Android schema. This declaration is crucial because it ensures that all defined attributes and resources are correctly interpreted and associated with their respective elements in the Android environment, providing the necessary contexts for UI components .

Android handles the rendering process of UI components defined in XML layout files by traversing the View tree in a pre-order manner. The Android UI framework asks each component to draw itself, beginning with the root view and descending through its child components. Each component renders itself in turn, ensuring that all views are appropriately painted on the screen according to their hierarchical relationships and specified attributes within the XML files .

FrameLayout is constrained by its simplicity as it only supports a single object reference at a time, pinning child elements to the top-left corner of the screen. Any additional child views are drawn over previous ones, potentially obscuring them unless transparency is applied, making precise control over layout visibility and interaction challenging. Its typical use cases include scenarios where a simple placeholder or background swapping is necessary, such as displaying a single image or introducing a temporary overlay screen .

TableLayouts offer the advantage of organizing elements into rows and columns, similar to HTML tables, without displaying border lines by default. They can be especially useful for displaying structured data where alignment across multiple lines is necessary. Each row is defined by a TableRow object, and cells within a row can contain various View objects. This makes TableLayouts particularly suited for grids or structured inputs that benefit from a tabular presentation, unlike more linear or relationally dependent layouts .

The View class serves as the fundamental building block for user interface components in Android. It occupies a rectangular area on the screen, handles drawing, and processes events (event handling). The View class is the superclass for all interactive UI components like buttons and text fields, functioning as the base for widgets. Additionally, it organizes views into a tree structure and facilitates properties like focus and visibility, essential for creating interactive user interfaces .

The 'layout_weight' attribute in a LinearLayout assigns an importance value to each child view, allowing it to dynamically allocate more of the free space in the parent view, thus influencing the composition significantly. A higher weight value allows a view to expand more than others if there's any remaining space. This attribute is essential for creating fluid layouts where components must adapt to changes in screen size or orientation, ensuring a balanced and visually appealing arrangement even with varying content sizes or device dimensions .

To integrate UI components from XML layouts into Java code in Android, developers use the 'setContentView(R.layout.layout_name)' method to load the layout. UI components are accessed through resource IDs defined in the XML, utilizing the 'findViewById(R.id.component_id)' method. The 'R' class, automatically generated by Android, helps track resource IDs. Furthermore, to handle events, such as button clicks, developers attach listeners to UI components, where methods like 'setOnClickListener' are used to define what actions occur in response to user interactions .

You might also like