+ All Categories
Home > Documents > Android Application Development -...

Android Application Development -...

Date post: 06-Feb-2018
Category:
Upload: lecong
View: 213 times
Download: 1 times
Share this document with a friend
41
4. Graphical User Interfaces | 1 Lesson 4. Graphical User Interfaces Graphical User Interfaces............................. 3 The Model-View-Control Pattern (MVC)........................3 How is this pattern seen by the Android developer?..........3 Getting ready to create MVC conforming solutions..............4 Fundamental GUI Building Blocks...............................4 The View Class................................................4 Using the Android Studio GUI Design Tool......................6 Basic Android Layouts.........................................7 The FrameLayout Class.......................................7 The LinearLayout Class......................................7 Relative Layout..............................................11 Example 4.1 Telling the position of a widget inside a RelativeLayout..................................................11 Example 4.2 Setting a Relative Layout with the WYSIWYG editor ................................................................12 Example 4.3 Designing the UI of a simple Login-App.........13 Table Layout.................................................14 Example 4.4 The Restaurant's Menu App – Using TableLayout. 14 Example 4.5 The ISBN app - Using the TableLayout...........15 Example 4.6 Stretching a TableLayout.......................16 ScrollView And HorizontalScrowView Containers................17
Transcript
Page 1: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 1

Lesson 4. Graphical User Interfaces

Graphical User Interfaces...................................................................................3

The Model-View-Control Pattern (MVC).......................................................3How is this pattern seen by the Android developer?..................................3

Getting ready to create MVC conforming solutions......................................4Fundamental GUI Building Blocks.................................................................4The View Class..............................................................................................4Using the Android Studio GUI Design Tool....................................................6Basic Android Layouts...................................................................................7

The FrameLayout Class..............................................................................7The LinearLayout Class..............................................................................7

Relative Layout...........................................................................................11Example 4.1 Telling the position of a widget inside a RelativeLayout......11Example 4.2 Setting a Relative Layout with the WYSIWYG editor............12Example 4.3 Designing the UI of a simple Login-App...............................13Table Layout...............................................................................................14Example 4.4 The Restaurant's Menu App – Using TableLayout...............14Example 4.5 The ISBN app - Using the TableLayout.................................15Example 4.6 Stretching a TableLayout.....................................................16ScrollView And HorizontalScrowView Containers........................................17Plumbing: Connecting GUI Design to Java Code.........................................17Example 4.7 Plumbing: Connecting XML widgets to Java objects.............17Basic Widgets: A minimalist approach........................................................19Example 4.8 The Café App - Making a discrete number of choices.........21Customizing a Widget.................................................................................24Using Material Design.................................................................................26

Page 2: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 2

Appendix 4.1 Disable-Enable Soft Keyboarding on an EditText View......27Appendix 4.2 ..................................................................EditText Boxes and Keyboards

28Example 4.9 Entering Title Caps and Predictive Typing............................29Example 4.10 Using inputType formats....................................................30

Page 3: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 3

Lesson 4Graphical User Interfaces

Goals

This lesson introduces Android’s way of building graphical user interfaces (known as GUI or UI). We will study a set of native Layout Design Patterns including Linear, Relative, and Tabular. We will learn how to create custom layouts based on combinations of those primitive patterns using Android’s Studio WYSIWYG Editor Tool. Alternatively, we will learn how to setup and edit layouts using their textual XML representation. Our custom GUIs will be constructed using a minimalistic set of widgets or graphical controls including text boxes, buttons, and selectors. We will learn how to connect GUI widgets with their representative Java objects. The lesson concludes with a non-trivial example app (CaféApp) that illustrates the use of tools and patterns discussed in this section.

The Model-View-Control Pattern (MVC)

Android apps are created using a strategy known as the Model-View-Controller (MVC) approach. MVC is an important software design pattern whose primary goal is to separate the three most fundamental components of an application: (1) user interface, (2) business logic, and (3) input logic. The interface exposes a face for the user to operate with the app, the business logic encapsulates the actual operations to be performed in response to the user’s requests, and the input logic deals with the process of capturing data and requests for the app to work.

How is this pattern seen by the Android developer? Model. Consists of the set of Java classes used to represent the problem

domain business entities managed by the application. As an example: Customers, Vendors, ItemsOrdered could be potential classes in a Shopping App.

View. Set of screens or faces presented by the application to the user. The screens not only display data but also provide an environment for the user-app interaction.

Controller. Implemented through the Android OS in the form of Activities, Services, Receivers, and Content Providers. Those components are responsible for the channeling and interpretation of the user and system

Page 4: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

inputs. The input may come from a variety of sources such as the keyboard, touchscreen gestures; GPS chip, proximity sensor, accelerometer, etc. Input tells the Model and/or the View (usually through callbacks and registered listeners) to change as appropriate.

Getting ready to create MVC conforming solutions

A word of caution is appropriated before we get immersed in the many details regarding the design of GUIs. Here is a list of facts the Android developer should be aware of,• Inputs could be sent to the application from various physical/software components.

Reacting to those signals is typically handled by callback methods. Usually there are many of them; you want to learn how to choose the appropriate one.

• Moving through lifecycle states should be harmoniously tied to the logic in the problem domain area. For instance, if forced to Pause you may want to save uncommitted data.

• Android’s notification mechanism is used to inform the user of important events happening outside the current application (such as arrival of a text message or email, low battery, fluctuations of the stock market, an approaching storm, etc.) and consequently choose how to proceed.

• Views are unlimited in terms of aesthetic and functionality. However physical constraints such as size, and hardware acceleration (or lack of) may affect how graphical components are managed.Android graphical interfaces are usually implemented as XML files (although they

could also be dynamically created from Java code). An Android UI is conceptually similar to a common HTML page. In a manner similar to a web page interaction, when the Android user touches the screen, the controller interprets the input and determines what specific portion of the screen and gestures were involved. Based on this information it tells the model about the interaction in such a way that the appropriate “callback listener” or lifecycle state could be called into action. Unlike a web application (which refreshes its pages after explicit requests from the user) an asynchronous Android background service could quietly notify the controller about some change of state (such as reaching a given coordinate on a map). In turn, the application reacts producing a change of the view’s state. Observe that all of these could occur without user intervention.

Fundamental GUI Building Blocks

Graphical designs are usually made through a space-allocation strategy similar to the process of diagramming a page for printing. In general, the process begins by targeting a particular screen format (tablet, phone, wearable, etc.) and filling this space with its root layout. Layouts are invisible structured containers used for holding other Views and nested layouts.

Page 5: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 5

Layouts can be partitioned into regions. Each region may include another layout container or a widget. The design process stops when each layout is holding a simple widget element. In the next sections, we will discuss layouts and widgets.

The View Class

The View class is the Android’s most basic component from which users interfaces are made. It acts as a container of displayable elements. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. Widgets are subclasses of View and accommodate UI components such as buttons, checkboxes, labels, text boxes, etc. Figure 4.1 illustrates a GUI design and its equivalent XML definition. The GUI employs a vertically oriented LinearLayout as is outermost root container. Inside of the screen region, there are four widgets. First, there is on top a TextView, immediately below there is an input-output EditText box, finally followed by two Buttons.

a. UI – Design View

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="top|center" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/txtCompanyName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="6dp" android:background="#90caf9" android:gravity="center" android:text="Top Label" android:textSize="30sp" android:textStyle="bold"/> <EditText android:id="@+id/txtComments" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff59d" android:hint="Enter comments here..." android:inputType="text"/> <Button android:id="@+id/btnSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:text="Small\nButton"/> <Button android:id="@+id/btnBig" android:layout_width="wrap_content"

Page 6: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

6 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

android:layout_height="wrap_content" android:layout_weight="2" android:ems="10" android:text="Big\nButton"/></LinearLayout>

b. UI – XML Text ViewFigure 4.1 A simple GUI and its equivalent XML definition.

An Android’s XML view file is a text-based description of a single GUI. It presents in a hierarchical disposition the placement and attributes of its contained elements. Each of the embedded XML elements could be widgets or user-defined nested layouts holding their own embedded viewgroups. GUIs are rendered on the device's screen whenever an Activity invokes the setContentView(R.layout.xmlfilename) method, where xmlfilename is the name of the XML specification. Dealing with the XML contained widgets and layouts typically involve the following operations:• Set properties: Adjust intrinsic component attributes. For instance, when working

with a TextView you may set the background color, text, font, alignment, size, padding, margin, etc.

• Set up listeners: Define acceptable user-app interactions. For example, an image could be programmed to respond to various events such as: click, long-tap, mouse-over, etc.

• Set focus: To set focus on a specific view, you call the method .requestFocus() or use XML tag <requestFocus />.

• Set visibility: You can hide or show views using setVisibility(…).

Using the Android Studio GUI Design Tool

You create and modify your application GUIs using the AS Screen Designer Tool (ASDT). This facility allows you to operate each screen using either a graphical WYSIWYG or textual XML editor. Figure 4.2 shows the image created for the HelloApp project introduced in Lesson 2. Remember that we used the automatic application wizard to manufacture the skeleton app; consequently, the structure shown in Figure 4.2 corresponds to the default disposition of files and names as prepared by the app wizard.

Android Studio considers all the XML-based layouts to be resources; layout files are stored in the app/src/res/layout directory inside your Android project (see the Project Pane on the top left portion of the figure). Our HelloApp screen specification is defined inside the file activity_main.xml. When you click on the layout file name, the ASDT is opened; you must decide which of its two possible faces should be exposed. You choices are a WYSIWYG editor (as shown in Figure 4.2) or its equivalent XML editor. You switch between those two options by clicking the tabs Design and Text (shown at the bottom of the ASDT screen).

GUIs are assembled using a drag-and-drop strategy. The design Palette Pane shows a collection of visual and organizational elements including layouts, widgets, text

Page 7: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 7

fields, containers, date & time pickers, and expert components. Think of the screen depicted to the right side of the Palette as the canvas on which you will paint your design. In practice, you will transfer instances of the Palette elements to the canvas as dictated by the specific needs of your application.

The Component Tree pane (located on the top right of the AST) provides a summary of the GUIs hierarchy. Click on any of its entries and focus will be set to that element on the canvas. The Properties Pane is used to assign specific values to the attributes of the object currently selected on the canvas. For instance, you may want to change the background color of a TextView to a particular color or set a bigger size to its font.

Figure 4.2. Android Studio Design Tool (ASDT) displaying the layout of HelloApp (see Lesson 2)

Basic Android Layouts

Android GUI Layouts are containers having a predefined structure and placement policy such as relative, linear horizontal, grid-like, etc. Layouts can be nested; therefore a cell, row, or column of a given layout could be another layout. The following figure displays the basic layout types offered by the Android Studio Palette.

Figure 4.3 Primitive Android Layout Types.

Page 8: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

8 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

The FrameLayout Class

The FrameLayout is the simplest form of graphical containment. When used, it becomes the outermost UI container holding the view hierarchy. It allows you to define how much of the screen (high, width) will be utilized. The placement of any children embedded into a FrameLayout is mandatorily set to the top left corner of the screen. Observe that no other arrangements could be enforced with a FrameLayout (see Figure 4.4 (a)).

The LinearLayout Class

The LinearLayout supports a filling strategy in which new elements are stacked either in a horizontally or vertically. If the layout has a vertical orientation, new rows are placed one on top of the others. A horizontal layout uses a side-by-side column placement policy (see Figure 4.4 (b)). Mastery of this pattern will allow you to build almost any practical UI design.

(a) FrameLayout (b) Nested LinearLayout showing vertical orientation

Figure 4.4 A sample of Frame and Linear Layouts respectively

Configuring a LinearLayout usually requires you to set the following attributes: orientation (vertical, horizontal) fill model (match_parent, wrap_contents) weight (0, 1, 2, …n ) gravity (top, bottom, center,…) padding ( dp – device independent pixels ) margin ( dp – device independent pixels )

Orientation

This clause defines the physical ordering of the elements placed inside the layout. The possible values for orientation are horizontal and vertical. Vertical orientation dictates a placement policy on which graphical elements are co-located one on top of the other from top to bottom. Horizontal orientation indicates that elements will be set inside of the layout using a side-by-side disposition going from left to right.

Page 9: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 9

Figure 4.5 A GUI design showing vertical and horizontal orientation respectively

Fill Model

Widgets have a “natural size” based on their included text (known as the rubber-band effect, observe that character ‘m’ is wider than ‘i’). Consequently, a TextView holding the string "iii" is narrower that other TextView showing the value "mmm". Note that on occasions, you may want your widget to have a specific space allocation (height, width) even if no text is initially provided (as is the case of the empty text box shown below).

Figure 4.6 A screen designed using (a) natural widget size, (b) Button set at 125dp, others match_parent

All widgets inside a LinearLayout must include ‘width’ and ‘height’ attributes. This dimensioning is accomplished using the clauses android:layout_width and android:layout_height. Values used in defining height and width can be:• A precise dimension such as 125dp (dp stands for device independent pixels, or dip

). This is a manufacturer's dependent value. As a reference, typical Samsung's pixelage is

640 x 360 dp Normal size screen 1024 x 600 dp Large screen 1280 x 800 dp XLarge screen

• wrap_content indicates the widget should adjust itself to its natural space. A TextView set to wrap_content may use the additional typographical specification android:ems="x" to reserve space for x occurrences of the ‘m’ character.

• match_parent (previously called ‘fill_parent’) indicates the widget wants to be as big as the enclosing parent.

Page 10: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

10 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

Weight

The extra space left unclaimed in a layout could be assigned to any of its inner components by setting its Weight attribute. The default value 0 is used when the view should not be stretched. The bigger the weight, the larger the proportion of extra space given to that widget.

For example, Figure 4.1 shows a GUI that includes a TextView, an EditText box, and two Buttons. The TextView and Button widgets do not claim any extra space (default property android:layout_weight="0") whereas the following buttons include the clauses android:layout_weight="1" and android:layout_weight="2" respectively. Once the four controls are drawn using their natural sizes, the system looks at the remaining free space and the explicit weight demands. In this case, the freeUI space is divided into three portions(1 + 2), one of them is added to the small button, and the remaining two are added to the large button. Playing with the weight property produces different renditions of visual scaling. Obseve that objects not declaring :weight, are drawn at their natural sizes

Layout_Gravity and Gravity

Layout_Gravity is used to indicate how a UI control will align on the screen. Positioning a widget is done considering the edges of its enclosing container. By default, widgets are left and top-aligned. You may use the XML property android:layout_gravity to set other possible arrangements, including: left, center, right, top, bottom, start, end, center_vertical, center_horizontal, etc. Figure 4.7(a) shows a GUI in which its button has right layout_gravity.

The android:gravity property is used to indicate how to place the contents of a container. Figure 4.7(b) shows a content-centered TextView control. Observe that the text box is top-left aligned, but the gravity of its enclosed text is "center". On Figure 4.7(c), the TextView's layout_gravity is "center", but its enclosed text uses the :gravity property to place its text using a "right" alignment.

(a) Button's layout_gravity set to 'right'

Caption's ems="9"  (width)

(b) TextView's gravity set to center

(c) gravity="right" and layout_gravity="center"

Figure 4.7 Portions of a GUI showing the effect of :layout_gravity and :gravity on a Button and a TextView

Padding and Marging

Padding and Margin represent the internal and external spacing between a widget and its included and surrounding context (respectively).

Page 11: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 11

Figure 4.8. Widget3 uses layout_marging to separate from its neighbors. It also sets internal padding.

The padding attribute specifies the widget’s internal margin (in dp units). The internal margin is the extra space between the borders of the widget's "cell" and the actual widget contents. Either use android:padding property or call method setPadding() at runtime. For instance, the code snippet below defines an EditText view and sets its padding to 30 dips.<EditText android:id="@+id/ediName" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:padding="30dp" />

The layout_marging attribute is used to increase the space between an element and its surrounding neighbors. Observe that by default, widgets are tightly displayed next to each other. For example, Widget3 in Figure 4.8, uses the layout_marging attribute to distance itself from its neighbors Widget1 and Widget2. At the same time, it has set an internal spacing, or padding, to separate its content from its own border.

Relative Layout

This is the default type used by the AS app making wizard. One may argue that it is easy to use, simple and effective in most cases. The placement of a widget in a RelativeLayout is based on its positional relationship to other widgets in the container as well as the parent container. Figure 4.9 (a) shows a screen including three widgets identified as A, B, and C. A referential way of describing the position of each element is as follows: A is at the parent’s top, C is below A, to its right, and B is below A, to the left of C. We will use this approach to create GUIs based on the RelativeLayout pattern. Figure 4.9 (b) shows how the placement of the button is recognized by the ASDT editor: "below: edtText1, alignRight: editText1". That is, the button is below the EditText box called editText1, and both of them are aligned with respect to the same right edge.

Page 12: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

12 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

(a) A simple screen holding three widgets

(b) Button's position described respect to EditText location

Figure 4.9. Two screens holding widgets embedded into a Relative Layout

Example 4.1 Telling the position of a widget inside a RelativeLayout

There are two ways to indicate the relative place of a graphical element inside a RelativeLayout (a) you may state its position respect to the container, and (b) you may indicate its location respect to other already established graphical element.

Figure 4.10 shows how a set of widget locations' are described based on their connection to the containing frame. Those clauses are called XML boolean positioning properties; when defined you set properties to either true or false values.

Figure 4.10 (a) Describing placement of widgets in a RelativeLayout based on their location respect to the

container.

Figure 4.11 summarizes the narrative used to describe the placement of a widget based on another widget already anchored in the layout. In each case assume that the location of widget "wid1" has already been defined. The statements in the figure below illustrate how the second widget ("wid2") describes its location based on "wid1".

Page 13: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 13

Figure 4.11 Mapping widgets respect to another already mapped control.

Example 4.2 Setting a Relative Layout with the WYSIWYG editor

The image below shows a screen designed with the Android Studio WYSIWYG Editor. We are trying to collocate the button identified as wid2. Observe that its placement is visually described using (green) lines referencing the already drawn wid1 view. Both views have the same bottom, same right, but wig2 has an elevation of 36 dps respect to wid1.

<Button android:id="@+id/wid2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/wid1" android:layout_alignRight="@+id/wid1" android:layout_marginBottom="36dp" android:text="@string/wid2" />

Figure 4-12 Placing a button in a Relative Layout

When using relative positioning, you need to assign identifiers (android:id="…" clause) to all elements that you will be referring to (those are the 'anchored' controls). XML elements are named using the prefix: @+id/. For instance an EditText box could be called: android:id="@+id/txtUserName". You must refer only to widgets that have been already defined. For instance, a new control to be positioned below the txtUserName EditText box could refer to it using android:layout_below="@+id/txtUserName".

Example 4.3 Designing the UI of a simple Login-App

Page 14: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

14 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

The following XML definition sketches the UI design of a typical login screen using a Relative layout. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myRelativeLayout" android:layout_width="match_parent" android:padding="16dp" android:layout_height="match_parent" > <TextView android:id="@+id/label_acme_login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ACME Corp. Login Screen" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/txtUserName" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:hint="Enter user Name" android:ems="15" android:layout_marginTop="23dp"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="15" android:hint="Enter Password" android:id="@+id/txtPassword" android:layout_below="@+id/txtUserName" android:layout_centerHorizontal="true"/>

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:id="@+id/btnCancel" android:layout_below="@+id/txtPassword" android:layout_alignEnd="@+id/txtPassword"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login" android:id="@+id/btnLogin" android:layout_below="@+id/txtPassword" android:layout_centerHorizontal="true"/></RelativeLayout>

Page 15: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 15

Table Layout

Android's TableLayout uses a grid pattern to position your widgets. In a manner similar to that of a spreadsheet, cells in the grid are identified by rows and columns. Columns are flexible; they could shrink or stretch to accommodate their contents. The element <TableRow> is used to define a new row in which widgets can be allocated. The number of columns in a TableRow is determined by the total of side-by-side widgets placed on the row.

Example 4.4 The Restaurant's Menu App – Using TableLayout

In the XML file below, a TableLayout defines two rows: the first row holds three TextView widgets, and the second row includes four widgets (three TextViews and a Button). Consequently, there will be at least four columns in the table, with column indices 0, 1, 2, 3 (observe that the last two TableRows are not shown).<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myTableLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" > <TableRow> <TextView android:background="#FF33B5E5" android:text="Item " /> <TextView android:layout_marginLeft="5dp" android:background="#FF33B5E5" android:text="Calories " /> <TextView android:layout_marginLeft="5dp" android:background="#FF33B5E5" android:text="Price $ " /> </TableRow> <View android:layout_height="1dp" android:background="#FF33B5E5" /> <TableRow> <TextView android:text="Big Mac" /> <TextView android:gravity="center" android:text="530" /> <TextView android:gravity="center" android:text="3.99" /> <Button android:id="@+id/btnBuyBigMac" android:gravity="center" android:text="Buy" /> </TableRow> <View android:layout_height="1dp" android:background="#FF33B5E5" /></TableLayout>

Page 16: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

16 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

Figure 4.13 A TableLayout design showing two rows holding 3, and 4 columns respectively.

Stretching Columns in a Table Layout

Widgets on a table’s row are placed lexicographically from left to right, beginning with the first available column. Each column in the table stretches as needed to accommodate its occupants.

The android:layout_span property indicates the number of columns the widget is allowed to expand.

Example 4.5 The ISBN app - Using the TableLayout

The table-based design shown below has four columns (indices: 0,1,2,3). The label “ISBN” goes in the first column (index 0). The EditText box to the right of the ISBN label relies on the layout_span attribute to be placed into a spanned set of three columns (columns 1 through 3). The second row holds two buttons (Cancel and Ok) occupying columns 2 and 3 respectively.

(a) Sketching a TableLayout

(b) Table shown by the WYSIWYG editorFigure 4.14 A spanning field inside of a TableLayout

The following XML listing is an equivalent representation of the screen shown above. Notice that the clause layout_column= "2", forces the Cancel button to appear in column 2 instead of column 0, which is the natural place for the first widget of a TableRow. We recommend experimenting with this XML specification; for instance, change the layout_span value from 3 to other values such as 1 and 2, 4. <?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myTableLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:background="@color/White" android:stretchColumns="1" android:orientation="vertical" > <TableRow>

Page 17: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 17

<TextView android:text="ISBN:" /> <EditText android:id="@+id/ediISBN" android:layout_span="3" /> </TableRow>

<TableRow> <Button android:id="@+id/cancel" android:layout_column="2" android:text="Cancel" /> <Button android:id="@+id/ok" android:text="OK" /> </TableRow>

</TableLayout>

Stretching the entire table

By default, a column is as wide as the “natural’ size of the widest widget collocated in this column (e.g. a column holding a button showing the caption “Go” is narrower than other column holding a button with the caption “Try again”). A table does not necessarily take all the horizontal space available. If you want the table to (horizontally) match its container use the property: android:stretchColumns="column(s)" where ‘column(s)’ is the position (or comma-separated set of positions) to be stretched in order to take up any space still available on the row. For example, the clause android:stretchColumns="0,2" can be used to stretch columns 0, and 2 of a table.

Example 4.6 Stretching a TableLayout

We will modify the table defined in Example 4.5 to elongate two of its columns. The corresponding XML code snippet and the new screen is shown below.

<TableLayout android:id="@+id/myTableLayout" xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@android:color/white" android:stretchColumns="2,3" android:padding="16dp">. . . same as in Example 4.5

Figure 4.15 Stretching columns to enlarge the entire table

Page 18: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

18 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

ScrollView And HorizontalScrowView Containers

The ScrollView control is useful in situations in which we have more data to show than what a single screen could display. ScrollViews provide vertical (up/down) sliding access to the data. The HorizontalScrollView provides a similar left/right sliding mechanism. Unlike the layouts previously discussed (i.e. Linear, Relative, and Table), the two scrolling containers can only include one child element. However, this child could be any kind of custom layout, representing hierarchies of an arbitrary degree of complexity.

Figure 4.16 includes examples of those containers. Please observe that although only a portion of the user’s data can be seen at one time, nonetheless the rest is available for viewing. <ScrollViewxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >

<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > . . . </LinearLayout>

</ScrollView>

Figure 4.16 Skeleton XML definition of a ScrollView (left), Scrolling Gestures: Up/Down and Left/Right (right)

Plumbing: Connecting GUI Design to Java Code

Once the GUI design has been completed, the next step is to implement its behavior. In terms of the MVC Pattern, we need to develop the Controller associated with the app's View. To accomplish this goal, the developer will create instances of the Android building blocks: Activities, Services, Broadcast Receivers, and Content Providers.

An app may include one or more instances of the Activity class. Commonly, each Activity instance is bound to a single GUI. Activities are responsible for implementing how the GUIs will react to the user's interactions. Specifically, we need to link each of the active GUI's XML elements –such as buttons, text boxes, check boxes, etc. - with their corresponding Java objects. The binding or plumbing setup is typically done in the onCreate(…) method of your main activity. After all the connections are made, your app should be ready to work with the user.

Example 4.7 Plumbing: Connecting XML widgets to Java objects

Page 19: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 19

Consider the login app depicted in Figure 4.17. The functionality of this app is quite simple. The user is expected to enter her name and later push the Go button to gain access to the rest of the application. Please observe that the XML file called "activity_main.xml", includes an EditText box named "@+id/edtUserName", as well as a button control named "@+id/btnGo". The notation "@+id/" stands for 'create an id'; it is required and prefixes the control's name.

Figure 4.17 Binding a GUI specification with corresponding Java classes

Let's now analyze the snippet of Java code on the right side of Figure 4.17. The onCreate method in the activity called MainActivity binds to the GUI through the statement setContentView(). The expression R.layout.activity_main is used to identify the layout to be shown. Individual XML widgets, such as btnGo is later associated with the Java application using the statement findViewByID(...). For instance: the expression Button btnGo= (Button) findViewById(R.id.btnGo) links the btnGo Button object with the "@+id/btnGo" graphical element. R is a class automatically generated to keep track of all resources available to the application. In particular "R.id" is the collection of object identifiers representing the widgets defined in the XML layout.

Once this GUI Object-to-Java Object plumbing operation has been completed, you may add listeners to your Java objects. Listeners will react to important events happening on the GUI. For instance, some important events are: clicking the btnGo button, changing text in the edtUserName box, touching the screen, etc. The following fragment illustrates how a click-event listener could be set on top of the btnGo button.Button btnGo = (Button) findViewById(R.id.btnGo);

btnGo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) {

Page 20: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

20 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

// get userName and validate against some database// more logic here...

}});

Other common ‘listeners’ that can be set to watch for user interactions include text-changed, long-press, item select, focus, etc.

Plumbing Multiple Buttons

The following example illustrates an alternative GUI-Java plumbing mechanism that may be used in cases in which your GUI contains several buttons. Observe how the MainActivity implements the OnClickListener interface. The mandatory onClick method checks which of the many buttons sent the tap signal and proceeds from there.public class MainActivity extends Activity implements OnClickListener { TextView txtMsg; Button btnBegin; Button btnExit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main ); txtMsg = (TextView) findViewById(R.id.txtMsg); btnBegin = (Button) findViewById(R.id.btnBegin); btnExit = (Button) findViewById(R.id.btnExit); btnBegin.setOnClickListener(this); btnExit.setOnClickListener(this); }//onCreate

@Overridepublic void onClick(View v) {

if (v.getId() == btnBegin.getId()) {txtMsg.setText("1-You clicked the 'BEGIN' button");

}if (v.getId() == btnExit.getId()) {

txtMsg.setText("2-You clicked the 'EXIT' button");}

}//onClick}

Basic Widgets: A minimalist approach

TextViews

A TextView is a rectangular area usually displaying a piece of non-editable text. A TextView (or caption) can be placed anywhere in the GUI, and its content can be aligned in multiple ways. Each TextView must indicate a height and width. In most cases, the space occupied by a caption is defined through the expressions: "wrap_content" or "match_parent". The value "wrap_content" refers to the natural size of the enclosed text, think of a rubber-band around the text. The expression 'match_parent' is

Page 21: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 21

used to indicate that the borders of the caption will coincide with those of its container. Another way of specifying a TextView width is to tell the fixed number of Device-Independent-Pixels occupied by the widget (e.g. android:height ="30dp"), or to indicate the amount of typographic Ms that fit in the box (e.g. android:ems="10"). <TextView android:id="@+id/labelCoffeeType" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#bf360c" android:text="What type of coffee?" android:textColor="@android:color/white" android:textStyle="bold" />

Other important attributes of a TextView are text, background color, textStyle, and textSize. The following is an example of the XML specification of a TextView.

Buttons

Android buttons are the most common type of GUI elements used to initiate application services. Buttons typically implement an 'onClick' event-handler routine responsible for triggering a method and channeling the available data (if any!) to the proper function. In its simplest form, a button only displays a caption (usually labeled with a verb), telling the user what is to suppose be done. However; an Android Button could be modified to include an image and text. The following XML snippet suggests how to accomplish this goal.<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_launcher" android:gravity="left|center_vertical" android:padding="15dp" android:text="Click me" />

EditText Boxes

The EditText widget is an extension of TextView that allows user’s input. In addition to plain text, this widget can display editable text formatted with HTML-styles such as bold, italics, underline, etc. This is done with Html.fromHtml(html_beautified_text). Moving data in and out of an EditText box is usually done in Java through the following accessor methods:

txtBox.setText("someValue") txtBox.getText().toString()

Input Type Formats

An EditText box could be set to accept input strings satisfying a particular pattern such as numbers (with and without decimals or sign), phones, dates, times, URIs, passwords, etc. Telling an EditText box to accept a particular choice of data type is done through

Page 22: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

22 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

the XML clause android:inputType="choices", where choices include any of the single values shown in Table 4.1.

inputType Formats used by EditText BoxesnonetexttextCapCharacterstextCapWordstextCapSentencestextAutoCorrecttextAutoCompletetextMultiLine

textImeMultiLinetextNoSuggestionstextUri textEmailAddresstextEmailSubjecttextShortMessagetextLongMessagetextPersonName

textPostalAddress textPasswordtextVisiblePasswordtextWebEditTexttextFiltertextPhonetictextWebEmailAddresstextWebPassword

numbernumberSignednumberDecimalnumberPasswordphonedatetimedatetime

Table 4.1 Text inputType Formats used by EditText boxes

You may combine any number of types, for instance the pair textCapWords|textAutoCorrect

accepts text capitalizing every word, and incorrect words are automatically changed (for instance ‘teh‘ is converted into ‘the’, and so on). An advantage of defining the inputType attribute for and EditText component is that as soon as the field gains focus, a specialized virtual keyboard will be offered at the bottom of the screen. For instance, when inputType is set to "number", the system shows a dedicated virtual keyboard that contains only numeric digits. For details on this issue, see Appendix 4.2 at the end of this lesson.

CheckBoxes and RadioButtons

A CheckBox is a special two-state button, which can be either checked or unchecked. A screen may include any number of mutually inclusive (independent) CheckBoxes. At any time, more than one CheckBox in the GUI could be checked. A radio button -in a manner similar to a CheckBox- is a two-state button that can be either checked or unchecked. Logically related radio buttons are normally put together in a RadioGroup container. The container forces the enclosed radio buttons to behave as mutually exclusive selectors. That is, the checking of one radio button unchecks all the others. You may call the method isChecked() to see if a specific RadioButton or CheckBox is selected, or change its state by calling toggle().Properties for font face, style, color, etc. are managed in a way similar to setting a TextView.

Example 4.8 The Café App - Making a discrete number of choices

We will use the application CaféApp to study the use of Radio and Checkboxes. In our example, the user will order a cup of coffee in two steps. First, our user will indicate what kind of coffee she prefers by choosing one base type out of three options (Decaf, Expresso, and Colombian). Later, the user will complete the order by adding additional add-ons such as Cream and/or Sugar. When the user taps on the "Pay" button, a brief message summarizing the coffee selections is flashed on the screen.

Example 4.8 CafeApp Layout Definition: activity_main.xml<?xml version="1.0" encoding="utf-8"?>

Page 23: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 23

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/White" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="csu.matos.MainActivity">

<TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#5b94f1" android:text="@string/kind_of_coffee" android:textColor="#ffffff" android:textStyle="bold"/> <RadioGroup android:id="@+id/radioGroupCoffeeType" android:layout_width="match_parent" android:layout_height="wrap_content"> <RadioButton android:id="@+id/radDecaf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/decaf"/>

<RadioButton android:id="@+id/radExpresso" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/expresso"/>

<RadioButton android:id="@+id/radColombian" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="@string/colombian"/> </RadioGroup>

<TextView android:id="@+id/labelCoffee" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#ff5b94f1" android:text="@string/coffee_addons" android:textColor="@android:color/white"

Page 24: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

24 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

android:textStyle="bold"/> <CheckBox android:id="@+id/chkCream" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cream" android:textStyle="bold"/> <CheckBox android:id="@+id/chkSugar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/sugar" android:textStyle="bold"/> <Button android:id="@+id/btnPay" android:layout_width="153dp" android:layout_height="wrap_content" android:text="@string/pay" android:textStyle="bold"/></LinearLayout>

Example 4.8 CafeApp. MainActivity.javapublic class MainActivity extends Activity {

CheckBox chkCream;CheckBox chkSugar;Button btnPay;

RadioGroup radCoffeeType;RadioButton radDecaf;RadioButton radExpresso;RadioButton radColombian;

@Overrideprotected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);

chkCream = (CheckBox) findViewById(R.id.chkCream);chkSugar = (CheckBox) findViewById(R.id.chkSugar);btnPay = (Button) findViewById(R.id.btnPay);

radCoffeeType = (RadioGroup) findViewById(R.id.radioGroupCoffeeType);

radDecaf = (RadioButton) findViewById(R.id.radDecaf);radExpresso = (RadioButton) findViewById(R.id.radExpresso);radColombian = (RadioButton) findViewById(R.id.radColombian);// LISTENER: wiring button-events-&-codebtnPay.setOnClickListener(new View.OnClickListener() {

@Overridepublic void onClick(View v) {

String msg = "Coffee ";if (chkCream.isChecked())

Page 25: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 25

msg += " & cream ";if (chkSugar.isChecked())

msg += " & Sugar";// get selected radio button ID numberint radioId = radCoffeeType.getCheckedRadioButtonId();// compare selected's Id with individual RadioButtons IDif (radColombian.getId() == radioId)

msg = "Colombian " + msg;// similarly you may use .isChecked() on each RadioButtonif (radExpresso.isChecked())

msg = "Expresso " + msg;// similarly you may use .isChecked() on each RadioButtonif (radDecaf.isChecked())

msg = "Decaf " + msg;Toast.makeText(getApplicationContext(), msg, 1).show();// go now and compute cost...

}// onClick});

}}

A good Android programming practice is not to enter immediate literal strings as attribute values inside XML assignment clauses. For example, assume you are defining a TextView to show a company headquarter’s location. In this case, a clause such as android:text="Cleveland" should not be used (observe it produces a Warning message: [I18N] Hardcoded string "Cleveland", should use @string resource). Instead, you should apply a two steps procedure in which first, you write the literal string –say headquarter – in the file res/values/string.xml. The resource string entry should be something like

<string name="headquarter">Cleveland</string>.

Later, whenever the string is needed, you provide a reference to the resource string entry using the notation @string/headquarter. For instance, in our example you should enter android:text="@string/headquarter". Notice that if the string is used in many places and its actual value changes, we just update the resource file entry once. It also provides support for internationalization – the text held inside resource strings can be easily changed from one language to another. The resource strings used in the CafeApp are listed below.

Example 4.8 CafeApp. res/values/strings<resources> <string name="app_name">CafeApp</string> <string name="kind_of_coffee">Kind of Coffee</string> <string name="decaf">Decaf</string> <string name="expresso">Expresso</string> <string name="colombian">Colombian</string> <string name="coffee_addons">What else in your coffee?</string> <string name="cream">Cream</string> <string name="sugar">Sugar</string> <string name="pay">Pay</string></resources>

Page 26: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

26 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

Customizing a Widget

The developer can modify the appearance and touch responses of a widget. For example, a button widget could be customized by changing its shape, border, color, margins, etc. Basic shapes include rectangle, oval, line, and ring. In addition to visual changes, the widget’s reaction to user's interaction could be adjusted for events such as Focused, Clicked, etc. Figure 4.19 shows a screen in which an EditText and Button widgets as normally displayed by a device running SDK4.3 (Ice Cream). The bottom two widgets (a TextView and a Button) are custom made versions of the two original controls.

The following code fragment defines the custom button widget. <Button android:id="@+id/btnCustomButton" android:layout_width="120dp" android:layout_height="wrap_content" android:background="@drawable/custom_button_spec" android:text="Custom Button" />

You need now to create the 'custom_button_spec.xml' XML file inside the res/drawable folder. The XML file contains the following specifications<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_pressed="true"> <shape android:shape="rectangle"> <corners android:radius="10dp"/> <solid android:color="#ffc0c0c0" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp"/> <stroke android:width="1dp" android:color="#ffFF6600"/> </shape> </item> <item android:state_pressed="false"> <shape android:shape="rectangle"> <corners android:radius="10dp"/> <solid android:color="#ffE0E6FF"/> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp"/> <stroke android:width="2dp" android:color="#ff777B88"/> </shape> </item></selector>

Page 27: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 27

Standard behavior:buttons turns bluewhen it is pressed down.

Custom behavior:button turns dark grey with an orange border when it is pressed down.

Figure 4.19 Customizing a Button Widget

The two faces of the custom button widget are based on the event named: state_pressed.That is, one face will be shown when state_pressed=true, and a second face for the case in which state_pressed=false. The Shape attribute specifies its solid color, padding, border (stroke) and corners (rounded corners have radius > 0 ).

You may also add an animation to the tapping of the button. For instance, you may attach the following simple alpha changing animation to the onClick event of modified btnCustomButtom. The animation will last 500 milliseconds and change the button's background from opaque to half-way transparent (an alpha level 1 means solid opaque color, while alpha level 0 means completely transparent). This animation is useful in conveying visual feedback confirming that the tapping action was initiated. Animation animation1 = new AlphaAnimation(1.0f, 0.5f); animation1.setDuration(200); v.startAnimation(animation1);

Using Material Design

Applications targeting SDK 5.0 (API level 21) and above, should consider adhering to the design recommendations outlined by Android's Material Design Strategy1. Material design includes guidelines for creating apps that consistently handle visual, motion, and interaction design choices across platforms and devices. For instance; there is a set of predefined color palettes that all applications in the Android eco-system should use in

1 Material design - Introduction. Visited June 30, 2017. https://www.google.com/design/spec/material-design/introduction.html#introduction-

principles

Page 28: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

28 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

order to convey a more consistent and harmonious look-and-feel appearance2. Each color palette includes a range of ten tones of the same color. The tones are identified by the base color and a number. For instance Red50, Red100, Red200 … Red900; where Red50 is the lightest and Red900 the darkest red tone and Red500 the primary color. There are also four complementary Accent colors called A100, A200, A300, and A400 (darkest).

Each app made by the AS wizard includes a basic color scheme described in an XML file called res/values/colors.xml. If you inspect this file, you will find three entries named colorPrimary, colorPrimaryDark, and colorAcent. The first two correspond to Color500 and Color900 of the Blue palette. Those color names are referenced by your app's res/values/styles.xml which in turn works with the app's theme management.

Figure 4.20 A Material Design conforming Red-Amber Palette (UpMaterial Design© is a product of UpLabs Inc.)

You may customize your app by choosing any palette combination that you like best. As an example, Figure 4.20 shows a mixed Red-Amber Material Design Palette selection. The color mixture was built by choosing two colors from the menu exposed by the on-line tool MaterialUp © 3. The tool produces a customized colors.xml resource file used to replace the default selection. You could to refer to tones defined in colors.xml. in expressions such as android:background="@colors/colorPrimary" or android:textColor="@colors/colorAccent".

2 Material design colors. Visited June 30, 2017. Link: http://www.google.com/design/spec/style/color.html#

3 MaterialUp ©. Available at https://www.materialpalette.com. Last visited June 30, 2017. This site is not affiliated to Google.

Page 29: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 29

Appendix 4.1 Disable-Enable Soft Keyboarding on an EditText View

To disable the action of the soft keyboard on an EditText you should set its input type to null, as indicated below: editTextBox.setInputType( InputType.TYPE_NULL );

To temporarily hide or display the virtual keyboard, call the following methods:public void showVirtualKeyboard() { Context context = getActivity().getApplicationContext(); ((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);}

public void hideVirtualKeyboard() { Context context = getActivity().getApplicationContext(); ((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); }

Page 30: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

30 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

Appendix 4.2 EditText Boxes and Keyboards

Keyboarding data into an Android application is functionally dependent on the hardware present in the actual device as well as the user's choice on the matter. There are units with permanently exposed physical keyboards, retractable keyboards, virtual keyboards, as well as voice recognition mechanisms for input.

When the user taps on an EditText box, the Input Media Framework (IMF) provides access to (a) a hard (or real) keyboard (if one is present) or (b) a soft (or virtual) keyboard known as IME that is the most appropriated for the current input type. You may close the virtual keyboard by tapping the hardware BackArrow key.

TextViews can use either XML clauses or Java code to tell the type of textual data they should accept. For example an XML specification for an EditText box could be: android:inputType="phone". The same effect would be achieved in Java code by issuing the statementeditTextBox.setInputType(android.text.InputType.TYPE_CLASS_PHONE);

Knowing the inputType associated to a field impacts the choosing of the best virtual keyboard for the current input class. The best keyboard will show only the symbols that are appropriate for the data field; this will simplify the act of entering data and reduce the chances of making mistakes.

IME QWERTY soft keyboard

Page 31: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 31

Example 4.9 Entering Title Caps and Predictive Typing

Using the XML clause android:inputType= " text|textCapWords"

After tapping on the EditText box to gain focus, a soft keyboard appears showing CAPITAL letters

After the first letter is typed, the keyboard automatically switches to LOWER case mode

After entering space the keyboard repeats cycle beginning with UPPER case, then LOWER case letters.

The user has previously selected English and Spanish as default languages in this device.

You may speed up typing by selecting an option from the list of suggested bilingual word choices.

The selected word is introduced in the EditText box

Page 32: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

32 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t

Example 4.10 Using inputType formats

Using android:inputType="number|numberSigned|numberDecimal"1. The keyboard displays numbers.2. Non-numeric keys (such as !@#$%&*?/_) are visible but

disable.3. Only valid numeric expressions can be entered.4. Type number|numberSigned accepts integers.5. Type numberDecimal accepts real numbers.Assume the EditText field is named: editTextBox, In Java code we could at run-time set the input method by issuing the command: editTextBox.setInputType( android.text.InputType.TYPE_CLASS_NUMBER |

android.text.InputType.TYPE_NUMBER_FLAG_SIGNED);

Using android:inputType="textPassword" Using android:inputType="textEmailAddress"

The keyboard displays all possible keys. Current character is briefly displayed for verification purposes. The current character is hidden and a heavy-dot is displayed instead of the input character.

Soft keyboard shows characters used in email addresses (such as letters, @, dot). Click on [?123 ] key (lower-left) for additional characters

Using android:inputType="phone"

Page 33: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

4 . G r a p h i c a l U s e r I n t e r f a c e s | 33

Request additional symbols

Soft keyboard displays the layout of a typical phone keypad plus additional non digit symbols such as: ( ) . / Pause Wait # - +

Using android:inputType="time"

Soft keyboard displays a numerical layout. Only digits and the colon character (":") can be used.When clicked, the Auxiliary button DONE will remove the keyboard from the screen (default behavior).

You may change the auxiliary button’s caption and set a listener to catch the click event on that button. To do that add the following entry to your EditText field XML specification android:imeAction="actionSend".

Later, your Java code could provide an implementation of the method: editTextBox.setOnEditorActionListener() {…} to do something with the event.

Page 34: Android Application Development - grail.cba.csuohio.edugrail.cba.csuohio.edu/.../book/Lesson04-Graphical-User-I…  · Web viewyout Design Patterns. ... A word of caution is appropriated

34 | A n d r o i d A p p l i c a t i o n D e v e l o p m e n t


Recommended