Transcript

1

1

CPET 565 Mobile Computing SystemsCPET/ITC 499 Mobile Computing

Building User Interface and Basic Applications

&

Lab 2-1 Shipping Calculator appReference

Android Programming Concepts, by Trish Cornez and Richard Cornez, pubslihed by Jones & Barlett Learning, pp. 89-184.

Paul I-Hai Lin, ProfessorSpring 2017

A Specialty Course Purdue University M.S. Technology Graduate Program

Dept. of Computer, Electrical and Information Technology

Purdue University Fort Wayne CampusProf. Paul Lin

2

Topics of Discussion Android User Interface Layout The View Class Text Input and Output Soft Keyboard Lab Example 2-1: Basic Input and the Shipping

Calculator; pp. 107-118

Android’s Form Widgets for User Interfaces Unique ID of a View Object and the R Class The ViewGroup Lab Example 2-2: Burger Calorie Calculator App

Prof. Paul Lin

2

3

Topics of Discussion Adaptive Design Concepts – Screens and Orientation Lab Example 2-3: Shipping Cost Calculator II – Adaptive

Design

TableLayout and TableRow Lab Example 2-4: Simple Calculator App and the

TableLayout

Container Views Using an Adapter Lab Example 2-5: Renaissance Painting App

Prof. Paul Lin

4

Android User Interface Android User Interface,

https://developer.android.com/guide/topics/ui/index.html All UI elements in an Android app are built using - View

and ViewGroup objects• View object – draws something on the screen that the user

can interact with• ViewGroup object – holds other View (and ViewGroup)

objects in order to define the layout of the interface

Visual objects can be created using• Java code, or• An external layout XML file

Android Studio• Graphical Layout tool – building external XML layout file

Prof. Paul Lin

3

5

Android User Interface Android User Interface,

https://developer.android.com/guide/topics/ui/index.html View Hierarchy of an Android UI Layout

Prof. Paul Lin

6

Android User Interface OnCreate() method for an Activity The layout file will be inflated on the screen when the

Activity is created.//HelloGoodByeApppublic class MainActivity extends Activity {...protected void onCreate(Bundle savedInstanceState) {//TASK 1: INFLATE THE MAIN SCREEN LAYOUT USED BY THE APP

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//TASK 2: ESTABLISH REFERENCES TO THE TEXTVIEW AND BUTTON

Button exclaimBtn = (Button) findViewById(R.id.button);greetingTextView = (TextView) findViewById(R.id.textView);

//TASK 4: REGISTER THE LISTENER EVENT FOR THE BUTTON

exclaimBtn.setOnClickListener(toggleGreeting);}

Prof. Paul Lin

4

7

Layout, https://developer.android.com/guide/topics/ui/declaring-layout.html

A Layout defines the visual structure for a UI. A Layout can be declared in two ways:

• In XML layout file• At run time

Six Standard Root Layout• LinearLayout• RelativeLayout• TableLayout• RowLayout• GridLayout• FrameLayout

Prof. Paul Lin

8

Layout, https://developer.android.com/guide/topics/ui/declaring-layout.html

Prof. Paul Lin

5

9

Layout Figure 2-1 Standard Layout Types

Prof. Paul Lin

10

Layout Figure 2-2 RelativeLayout elements

Prof. Paul Lin

6

11

RelativeLayout – Figure 2-2<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent”

<TextViewandroid:text="Text 1"android:id="@+id/text1"

android:layout_alignParentTop="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginleft="65dp"android:layout_marginTop="86dp"/>

Prof. Paul Lin

12

RelativeLayout – Figure 2-2<TextView

android:text="Text 2"android:id="@+id/text2"android:layout_below="@+id/text1"android:layout_alignLeft="@+id/text1"android:layout_alignStart="@+id/text1"android:layout_marginTop="51dp"/>

<Buttonandroid:text="Button"android:id="@+id/button"android:layout_alignBottom="@+id/text2"android:layout_toRightOf="@+id/text2"android:layout_marginleft="95dp"/>

Prof. Paul Lin

7

13

RelativeLayout – Figure 2-2<TextView

android:text="Text 3"android:id="@+id/text3"android:layout_below="@+id/button"android:layout_alignLeft="@+id/button"android:layout_alignStart="@+id/button" android:layout_marginTop="57dp"/>

</RelativeLayout>

Prof. Paul Lin

14

Layout - GridLayout Figure 2-3 A GridLayout has two orientation

Prof. Paul Lin

8

15

Layout - GridLayout Figure 2-3 A GridLayout has two

orientation<GridLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"android:layout_width="match_parent"

android:layout_height="match_parent"android:columnCount="2"android:rowCount="2"android:orientation="horizontal">

Prof. Paul Lin

<TextViewandroid:text="Text 1" />

<TextViewandroid:text="Text 2"/>

<TextViewandroid:text="Text 3" />

<TextViewandroid:text="Text 4"/>

</GridLayout>

16

Layout Figure 2-4 FrameLayouts contain a single control object, such as a

canvas or list

Prof. Paul Lin

9

17

The View Class

The View class is the basic building block for UI in Android, https://developer.android.com/reference/android/view/View.html• Android.view.View

Using Views – arranged in a single “tree” in one or more XML layout files

Vies subclasses for building control objects: • Buttons, input/output text elements, radio buttons, checkboxes• Displaying text, images, or other content

Prof. Paul Lin

18

The View Class

Button View in XML layout file is defined using a set of attributes: • Width, height, alignment, background color• Handler method – respond to an onClick event

<Buttonandroid:id=“@+id/button1”android:layout_width=“wrap_content”android:layout_width=“20dp”android:layout_alignParentTop=“true”android:layout_centerHorizontal=“true”android:onClick=“goTap”android:background=“blue”android:text=“Button” />

Prof. Paul Lin

10

19

The View Class

Button View in XML layout file is defined using a set of attributes: • Width, height, alignment, background color• Handler method – respond to an onClick event

View class methods• Retrieve location/position of a View object: getLeft(), getTop(),

getRight(), getBottom()• Size, padding and margin: getMeasureHeight(),

getMeasuredWidth(): setPadding(int, int, int, int), setPaddingRelative(int, int, int, int), getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom()

Prof. Paul Lin

20

The View Class

Event Handling and Threading (basic cycle) An event occurs => dispatched to the appropriate view The view handle (Handler) the event and notifies any

event listeners. If the view’s bound may need to be changed => call

requestLayout() method If view’s appearance may need to be changed => call

invalidate() method If either requestLayout() or invalidate() were called, the

framework => measuring, laying out, and drawing the tree as appropriate

Prof. Paul Lin

11

21

Text Input and Output

Text Input/Text Output – Text Field class handling• TextView – for text output• EditText – allows text input and editing by the user

TextView class, https://developer.android.com/reference/android/widget/TextView.html

EditText class, https://developer.android.com/reference/android/widget/EditText.html• Allow text input and editing by the user• A range of input types: number, date, password, email

address• InputType properties:

textCapSentences, textCapCharacters, textCapWords textAutoCorrect, textAutoComplete, textNoSuggestions textUri, textShortMessage, textLongMessage textWebEditText, textPhoneticProf. Paul Lin

22

Text Input and Output Text Fields that Defines the EditView Control

Text Field inputType Property Value• Plant Text None• Person Name textPersonName• Password textPassword• Password (Numeric) numberPassword• Email textEmailAddress• Phone phone• Postal Address textPostalAddress• MuitilineText textMultipLine• Time time• Date date• Number number• Number (signed) numberSigned• Number (decimal) numberDecimal

Prof. Paul Lin

12

23

EditText

InputType properties is used to reconfigure the soft keyboard

Prof. Paul Lin

24

EditText

Figure 2-6 A softkeybord configured for the input of an email address

Prof. Paul Lin

13

25

EditText

Figure 2-7 A softkeybord configured for password input

Prof. Paul Lin

26

EditText

Figure 2-8 Android supports multiple softkeybordconfiguration

Prof. Paul Lin

14

27

EditText

Figure 2-9 Text AutoComplete will produce dictionary-based suggestions during input

Prof. Paul Lin

28

EditText

InputType properties is used to reconfigure the soft keyboard

<LinearLayoutxmlns:android=“http://schemas.android.com/apk/res/android”

android:orientation=”vertical”android:layout_width=”match_parent”android:layout_height=”match_parent”

<EditTextandroid:layout_width=“match_parent”android:layout_height=”wrap_content”andorid:id=“@+id/editText”android:hint=”Name”android:inputType=“textCapWords|textPersonName”/>

</LinearLayout>

Prof. Paul Lin

15

29

Figure 2-10 The search icon appears when you declare android:imeOptions=“autoSearch”

<EditTextandorid:id=“@+id/editText” android:layout_width=“fill_parent”android:layout_height=”wrap_content”android:hint=”@string/search_hint”android:imeOptions=“actionSearch”/>

imeOptions property: actionSend, actionDone, actionGo, actionNext, actionPrevious

Prof. Paul Lin

30

Lab Example 2-1: Shipping Cost Calculator

Figure 2-11 A Sketched Prototype

Prof. Paul Lin

16

31

Lab Example 2-1: Shipping Cost Calculator

Figure 2-12

Prof. Paul Lin

32

Lab Example 2-1: Shipping Cost Calculator

Figure 2-13 View objects arrangement in the Layout Editor’s Design mode

Prof. Paul Lin

17

33

Lab Example 2-1: Shipping Cost Calculator

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.lin.shippingcalculator" ><application

android:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activity

android:name=".MyActivity"android:label="@string/app_name" ><intent-filter>

<action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity>

</application></manifest>

Prof. Paul Lin

34

Lab Example 2-1: Shipping Cost Calculator

//activity_my.xml .. See text book pp. 111-113<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin"android:background="@drawable/shippingbck"tools:context=".MyActivity">

Prof. Paul Lin

18

35

Lab Example 2-1: Shipping Cost Calculator

<!-- WEIGHT INPUT SECTION --><TextView

android:id="@+id/textView1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:text="@string/weightLBL"android:textAppearance="?android:attr/textAppearanceLarge"android:gravity="center_horizontal" />

Prof. Paul Lin

36

Lab Example 2-1: Shipping Cost Calculator

<!-- WEIGHT INPUT EDIT TEXT FIELD RECEIVES FOCUS --><EditText

android:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView1"android:layout_centerHorizontal="true"android:layout_marginTop="5dp"android:ems="10"android:gravity="center_vertical|center_horizontal"android:inputType="number"android:selectAllOnFocus="true"android:textSize="35sp"android:hint="@string/zero">

<requestFocus /></EditText>

Prof. Paul Lin

19

37

Lab Example 2-1: Shipping Cost Calculator

<TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/editText1"android:layout_centerHorizontal="true"android:text="@string/ouncesLBL"android:textAppearance="?android:attr/textAppearanceSmall" />

Prof. Paul Lin

38

Lab Example 2-1: Shipping Cost Calculator

//menu/my.xml<menu xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"tools:context=".MyActivity" ><item android:id="@+id/action_settings"

android:title="@string/action_settings"android:orderInCategory="100"android:showAsAction="never" />

</menu>

//res/values/dimens.xml<resources>

<!-- Default screen margins, per the Android Design guidelines. --><dimen name="activity_horizontal_margin">16dp</dimen><dimen name="activity_vertical_margin">16dp</dimen><dimen name="output_margin_buffer">30dp</dimen>

</resources>

Prof. Paul Lin

20

39

Lab Example 2-1: Shipping Cost Calculator

//res/values/strings.xml<?xml version="1.0" encoding="utf-8"?><resources>

<string name="app_name">Shipping Calculator</string><string name="hello_world">Hello world!</string><string name="action_settings">Settings</string>

<string name="weightLBL">Weight of the package</string><string name="ouncesLBL">(in ounces)</string><string name="baseLBL">Base Cost:</string><string name="addCostLBL">Added Cost:</string><string name="totalLBL">Total Shipping Cost:</string><string name="zeroDec">$0.00</string><string name="zero">0</string>

</resources>

Prof. Paul Lin

40

Lab Example 2-1: Shipping Cost Calculator

// ShipItem.javapackage com.example.lin.shippingcalculator;/*** Created by trishcornez on 6/29/14.*/

public class ShipItem {// SHIPPING CONSTANTSstatic final Double BASE = 3.00;static final Double ADDED = .50;static final int BASE_WEIGHT = 16;static final double EXTRA_OUNCES = 4.0;

// DATA MEMBERSprivate Integer mWeight;private Double mBaseCost;private Double mAddedCost;private Double mTotalCost;

Prof. Paul Lin

21

41

Lab Example 2-1: Shipping Cost Calculator

// ShipItem.java .. Continuepublic ShipItem() {

mWeight = 0;mAddedCost = 0.0;mBaseCost = BASE;mTotalCost = 0.0;

}public void setWeight (int weight){

mWeight = weight;computeCosts();

}

Prof. Paul Lin

42

Lab Example 2-1: Shipping Cost Calculator

// ShipItem.java .. Continueprivate void computeCosts() {

mAddedCost = 0.0;mBaseCost = BASE;

if (mWeight <= 0)mBaseCost = 0.0;

else if (mWeight > BASE_WEIGHT)mAddedCost = Math.ceil((double) (mWeight - BASE_WEIGHT) /

EXTRA_OUNCES) * ADDED;

mTotalCost = mBaseCost + mAddedCost;}

Prof. Paul Lin

22

43

Lab Example 2-1: Shipping Cost Calculator

// ShipItem.java .. Continuepublic Double getBaseCost() {

return mBaseCost;}

public Double getAddedCost() {return mAddedCost;

}

public Double getTotalCost() {return mTotalCost;

}}}

Prof. Paul Lin

44

Lab Example 2-1: Shipping Cost Calculator

// MyActivity.java package com.example.lin.shippingcalculator;

import android.app.Activity;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;

import android.view.Menu;import android.view.MenuItem;import android.widget.EditText;import android.widget.TextView;

Prof. Paul Lin

23

45

Lab Example 2-1: Shipping Cost Calculator

// MyActivity.java .. Continuepublic class MyActivity extends Activity {

//DATA MODEL FOR SHIP ITEMprivate ShipItem shipItem;

//VIEW OBJECTS FOR LAYOUT UI REFERENCEprivate EditText weightET;private TextView baseCostTV;private TextView addedCostTV;private TextView totalCostTV;

@Overrideprotected void onCreate(Bundle savedInstanceState) {

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

Prof. Paul Lin

46

Lab Example 2-1: Shipping Cost Calculator

// MyActivity.java .. Continue//CREATE THE DATA MODEL FOR STORING THE ITEM TO BE SHIPPED

shipItem = new ShipItem();

//TASK 3: ESTABLISH THE REFERENCES TO INPUT WEIGHT ELEMENTweightET = (EditText) findViewById(R.id.editText1);

//TASK 3: ESTABLISH THE REFERENCES TO OUTPUT ELEMENTSbaseCostTV = (TextView) findViewById(R.id.textView4);addedCostTV = (TextView) findViewById(R.id.textView6);totalCostTV = (TextView) findViewById(R.id.textView8);

//TASK 4: REGISTER THE LISTENER EVENT FOR WEIGHT INPUTweightET.addTextChangedListener(weightTextWatcher);

}

Prof. Paul Lin

24

47

Lab Example 2-1: Shipping Cost Calculator

// MyActivity.java .. Continueprivate TextWatcher weightTextWatcher = new TextWatcher() {//THE INPUT ELEMENT IS ATTACHED TO AN EDITABLE,//THEREFORE THESE METHODS ARE CALLED WHEN THE TEXT IS CHANGED

public void onTextChanged(CharSequence s,int start, int before, int count){

//CATCH AN EXCEPTION WHEN THE INPUT IS NOT A NUMBERtry {

shipItem.setWeight((int) Double.parseDouble(s.toString()));}catch (NumberFormatException e){

shipItem.setWeight(0);}displayShipping();

}public void afterTextChanged(Editable s) {}public void beforeTextChanged(CharSequence s,

int start, int count, int after){}};

Prof. Paul Lin

48

Lab Example 2-1: Shipping Cost Calculator

// MyActivity.java .. Continueprivate void displayShipping() {

//DISPLAY THE BASE COST, ADDED COST, AND TOTAL COSTbaseCostTV.setText("$" + String.format("%.02f",

shipItem.getBaseCost()));addedCostTV.setText("$" + String.format("%.02f",

shipItem.getAddedCost()));totalCostTV.setText("$" + String.format("%.02f",

shipItem.getTotalCost()));}

Prof. Paul Lin

25

49

Lab Example 2-1: Shipping Cost Calculator

// MyActivity.java .. Continue@Override

public boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu, menu);return true;

}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {

return true;}return super.onOptionsItemSelected(item);

}} Prof. Paul Lin

50

Lab Example 2-1: Shipping Cost Calculator

Prof. Paul Lin

26

Summary

Q/A?

Prof. Paul Lin 51


Recommended