Вы находитесь на странице: 1из 121

Android application beginner

Tutorial reference

Android Application )

) jdk1.7.0
https://dl.dropbox.com/u/94729309/jdk1.7.0.rar
install

) Eclipse
http://eclipse.stu.edu.tw/technology/epp/downloads/release/juno/R/eclipse-mobile-juno-win32.zip
eclipse-mobile-juno-win32.zip unzip eclipse D drive (
D drive D drive )

) Android SDK
http://dl.google.com/android/installer_r20.0.1-windows.exe
installer_r20.0.1-windows.exe run Next
Install just for me Next
Destination floder application Browse
Install click
Next
Finish

) Tools Android 3.0 check Install 5 packages


(4.2 3.0 3.0 )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
) eclipse eclipse double click
) Workspace application OK click
) Android Developer Toos (ADT) plug-in (ADT plug-in download offline install
)
Help>Install New Software>
Add click

Ok

Next

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Connection
android application software

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( ) htarhtarlwin.blogspot.com

Android Application ( )

Hello world! Application

eclipse open

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Project create

File>New>Android Application Project

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Next click Minimum Required SDK 2.2 application

Android version 2.2 install application sdk version 3.0

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Browse (application logo

Next )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Next

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Install/Upgrade click

( install )

Accept All Install click

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
project create
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
(1) (Android version 2.2 ) USB debugging check

(2) Phone USB Cable

(3) Run>Run

(4) device OK

(5) Phone Hello World!

(6) menu Droid1 application touch

Hello world! application uninstall

(Settings>Applications>Manage applications

apk file

bin Droid1.apk install

software ( )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
data

select button click ( )

Android Application ( )

Run on Emulator

Android application android device ( /tablet/note)

(emulator) run

( ) project real device run emulator run emulator

run

Android Virtual Device Manager

eclipse tool bar Android Virtual Device Manager tool click

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
( RAM 1024 512 or 256 or 128 )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
HHl Start click

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
eclipse ( ) application Run

Hello world! emulator

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

( ) create Droid1 coding application

run Hello World!

Eclipse

Package Explorer Droid1>src>com.example.droid1>DroidActivity.java

package com.example.droid1;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.TextView;//*****

public class DroidActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

TextView tv = new TextView(this);//*****

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
tv.setText("Hello! I'm Dr. Htar Htar Lwin");//*****

setContentView(tv);//*****

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

return true;

//*****

phone run Emulator run run

Android Application ( )

Discussion

tutorial

Android SDK

install install

D: drive D:\sdk sdk

D drive

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Start SDK Manager check latest SDK tools platform

download platform check Install * packages click (*

= number of packages)

Android 4.2 download ( )

sdk folder (Android SDK install ) SDK Manager

eclipse download unzip

Eclipse IDE eclipse

Eclipse android application ADT Plugin install

Project create eclipse command line tools

eclipse

create application run run emulator

run

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

SDK 2.2 3.0

User Interface

) Tool bar create a new Android project tool click Next

click

( ) Next

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
MyApp2>res>layout>activity_main.xml code copy

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
<?xml version="1.0" encoding="utf-8"?>

<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="horizontal">

<EditText android:id="@+id/edit_message"

android:layout_weight="1"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:hint="@string/edit_message" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/button_send" />

</LinearLayout>

MyApp2>values>strings.xml code

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

<resources>

<string name="app_name">My First App</string>

<string name="edit_message">Enter a message</string>

<string name="button_send">Send</string>

<string name="menu_settings">Settings</string>

<string name="title_activity_main">MainActivity</string>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
</resources>

Run emulator run Textbox Button

run bin apk

install (coding ) )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

( ) coding

textbox button

textbox button layout

For layout

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

<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"

screen width and height

android:orientation="horizontal"

textbox button

Textbox

<EditText android:id="@+id/edit_message"

android:layout_weight="1"

android:layout_width="0dp"

android:layout_height="wrap_content"

textbox width and height

android:hint="@string/edit_message" />

button

<Button

android:layout_width="wrap_content"

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
android:layout_height="wrap_content"

android:text="@string/button_send" />

</LinearLayout>

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

<resources>

<string name="app_name">My First App</string>

Application name

<string name="edit_message">Enter a message</string>

Application run textbox string Enter a message

<string name="button_send">Send</string>

Application run button string Send

<string name="menu_settings">Settings</string>

<string name="title_activity_main">MainActivity</string>

</resources>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

( project

textbox button create textbox button

display MyApp

Open MyApp>res>layout>activity_main.xml

Add android:onClick="sendMessage" as follow:

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/button_send"

android:onClick="sendMessage" /> ( )

Open MyApp>src>MainActivity.java

Add these codes.

package com.example.myfirstapp;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.Menu;

import android.view.View;

import android.widget.EditText;

public class MainActivity extends Activity {

public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
/** Called when the user clicks the Send button */

public void sendMessage(View view) {

Intent intent = new Intent(this, DisplayMessageActivity.class);

EditText editText = (EditText) findViewById(R.id.edit_message);

String message = editText.getText().toString();

intent.putExtra(EXTRA_MESSAGE, message);

startActivity(intent);

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.activity_main, menu);

return true;

Tip: In Eclipse, press Ctrl + Shift + O to import missing classes

Now you need to create the DisplayMessageActivity class in order for this to work.

To create DisplayMessageActivity class

1. Click New in the toolbar.

2. In the window that appears, open the Android folder and select Android Activity. Click Next.

3. Select BlankActivity and click Next.

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
4. Fill in the activity details:

o Project: MyFirstApp

o Activity Name: DisplayMessageActivity

o Layout Name: activity_display_message

o Navigation Type: None

o Hierarchial Parent: com.example.myfirstapp.MainActivity

o Title: My Message

Click Finish.

Figure 1. The new activity wizard in Eclipse.

Open the DisplayMessageActivity.java file.

The class already includes an implementation of the required onCreate() method.

There's also an implemtation of the onCreateOptionsMenu() method, but you won't need it for this app so

you can remove it.

The class should look like this:

public class DisplayMessageActivity extends Activity {

@Override

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_display_message);

All subclasses of Activity must implement the onCreate() method.

The system calls this when creating a new instance of the activity.

It is where you must define the activity layout and where you should perform initial setup for the activity

components.

Add it to the manifest

You must declare all activities in your manifest file, AndroidManifest.xml, using an <activity> element.

You used the Eclipse tools to create the activity, it creates a default entry.

It should look like this:

<application ... >

...

<activity

android:name=".DisplayMessageActivity"

android:label="@string/title_activity_display_message" >

<meta-data

android:name="android.support.PARENT_ACTIVITY"

android:value="com.example.myfirstapp.MainActivity" />

</activity>

</application>

Receive the Intent

Every Activity is invoked by an Intent, regardless of how the user navigated there.

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
You can get the Intent that started your activity by calling getIntent() and retrieve the data contained

within it.

In the DisplayMessageActivity classs onCreate() method, get the intent and extract the message delivered

by MainActivity:

Intent intent = getIntent();

String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

Display the Message

To show the message on the screen, create a TextView widget and set the text using setText().

Then add the TextView as the root view of the activitys layout by passing it to setContentView().

The complete onCreate() method for DisplayMessageActivity now looks like this:

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Get the message from the intent

Intent intent = getIntent();

String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

// Create the text view

TextView textView = new TextView(this);

textView.setTextSize(40);

textView.setText(message);

// Set the text view as the activity layout

setContentView(textView);

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
}

Finally, DisplayMessageActivity class looks like this:

package com.example.myfirstapp;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.TextView;

public class DisplayMessageActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Get the message from the intent

Intent intent = getIntent();

String message = intent.getStringExtra(MainActivity. EXTRA_MESSAGE);

// Create the text view

TextView textView = new TextView(this);

textView.setTextSize(40);

textView.setText(message);

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
// Set the text view as the activity layout

setContentView(textView);

You can now run the app.

When it opens, type a message in the text field, click Send, and the message appears on the second

activity.

Figure 2. Both activities in the final app, running on Android 4.0.

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application (9) htarhtarlwin.blogspot.com

Android Application ( )

Android device current time display application

project create

Project name skeleton activity name Now

Now.java file source code

package com.example.skeleton;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import java.util.Date;

public class Now extends Activity implements View.OnClickListener {

Button btn;

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

btn = new Button(this);

btn.setOnClickListener(this);

updateTime();

setContentView(btn);

public void onClick(View view) {

updateTime();

private void updateTime() {

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

Discussion

package com.example.skeleton;

package declare

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import java.util.Date;

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
program class import android-specific class android

package

public class Now extends Activity implements View.OnClickListener {

Button btn;

Activity Now public class android.app.Activity base class extend

program Now button (btn) hold (Button android widget

widget application UI element Widget View

base class extend )

Button click activity trap Now OnClickListener

implement

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

btn = new Button(this);

btn.setOnClickListener(this);

updateTime();

setContentView(btn);

Activity onCreate() method invoke

The first thing you should do is chain upward to the superclass, so the stock Android activity initialization

can be done.

button instance create button click instance

setOnclickListener() updateTime() method

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
program run button current time display

setContentView()

public void onClick(View view) {

updateTime();

Button click button configure onClickListener instance onClick()

method invoke updateTime method call

button click

private void updateTime() {

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

Activity open button click button label current time

setText()

program run tap current time

tap

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
onCreate() method updateTime() run run run current time

tap current time

Android Application ( )

Widget create activity attach Java code

) XML-based layout file

XML-based layout widget relationship widget

continer relationship XML-based layout resource

layout file res folder

XML element attribute properties widget

container properties Button element attribute value

android:textStyle = bold button text bold

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
layout aapt tool R.java file generate layout

layout widget R.layout.main or R.id.button

xml code button project create

NowRedux layout name main xml code

res/layout main.xml file run button

button tap button

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

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

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="" />

</RelativeLayout>

XML layout file button create

xmlns:android="http://schemas.android.com/apk/res/android"

Root element Android XML namespace declare element root

children name space declaration inherit

android:id="@+id/button"

button jave code identifier android:id attribute

element id java code element id

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Button

Button XML element Button Android-supplied widget class

name widget android.view.View subclass

create full package declaration com.example.MyWidget

android:layout_width="wrap_content"

android:layout_height="wrap_content"

button width height

android:text=""

button text space

button XML code main.xml res/layout layout file

java code access NowRedux.java file onCreate() call back

setContentView(R.layout.main);

statement

button

findViewById();

java code NowRedux.java

package com.example.layouts;

import android.app.Activity;

import android.os.Bundle;

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
import android.view.View;

import android.widget.Button;

import java.util.Date;

public class NowRedux extends Activity

implements View.OnClickListener {

Button btn;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

btn=(Button)findViewById(R.id.button);

btn.setOnClickListener(this);

updateTime();

public void onClick(View view) {

updateTime();

private void updateTime() {

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

run button tap

program button XML code

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

Employing Basic Widget

widget Widget filed, label, button

Assigning Labels

Label android TextView user edit

textbox user box

label textbox

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Label create TextView instance create XML layout file

TextView element create button android:

text property text properties

android:typeface

monospace

android:textstyle

bold, italic or bold and italic

android:textColor

RGB hex format #FF0000

project create Label activity name main

main.xml file code run

<TextView xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/TextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="You were expecting something profound" />

output

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Fields of Green. Or Other Colors.

Edit Text

Edit Text widget TextView subclass Edit Text properties

android:autoText

auto spelling

android:capitalize

capital auto

android:digits

digit

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
android:singleline

single line or multiline

android:numeric

numeric-only input

android:password

password input

android:phoneNumber

phone number

Field project create activity name FieldDemo

main.xml code

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

<EditText xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/field"

android:layout width="fill parent"

android:layout height="fill parent"

android:singleLine="false"

/>

android:singleLine false

FieldDemo.java file code

package com.commonsware.android.basic;

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
import android.app.Activity;

import android.os.Bundle;

import android.widget.EditText;

public class FieldDemo extends Activity {

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

EditText fld=(EditText)findViewById(R.id.field);

fld.setText("Licensed under the Apache License, Version 2.0 " +

"(the \"License\"); you may not use this file " +

"except in compliance with the License. You may " +

"obtain a copy of the License at " +

"http://www.apache.org/licenses/LICENSE-2.0");

Run

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
https://dl.dropbox.com/u/94729309/how%20to%20write%20android%20application%20%2813%29.docx

Android Application ( )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
1. trivia game design

2. application prototype ( ) implement

3. game prototype run

1. Designing an Android Trivia Game

game user

Great white sharks diving

game Been, Done That!

1.1. Determining High-Level Game Features

features

Application name, version and developer splash sequence

Scores

Game rules

Game settings

feature main menu

user application

Been There, Done That! application screen

1. A startup screen

2. A main menu screen

3. A game play screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
4. A settings screen

5. A scores screen

6. A help screen

screen Been There, Done That! application user interface

1.2. Determining Activity Requirements

Screen activity class Figure 6.1 activity

Base Activity class QuizActivity activity

1. QuizActivity: android.app.activity class extend application preferences

application-wide settings and features class define

2. QuizSplashActivity: QuizActivity extend splash screen

3. QuizMenuActivity: QuizActivity extend main menu screen

4. QuizHelpActivity: QuizActivity extend help screen

5. QuizScoresActivity: QuizActivity extend scores screen

6. QuizSettingsActivity: QuizActivity extend settings screen

7. QuizActivity extend game screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
1.3. Determining Screen-Specific Game Features

Activity basic features define

1.3.1. Defining Splash Screen Features

Splash screen application entry point functionality (code)

QuizSplashActivity class screen

Application name and version

Game graphic or logo

main menu screen

Figure 6.2 splash screen

1.3.2. Defining Main

Menu Screen Features

Main menu screen screen Main menu screen splash

user screen functionality

QuizMenuActivity class main menu screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Splash screen main menu screen

User Play Game, Settings, Scores, or Help

Figure 6.3 main menu screen

1.3.3. Defining Help Screen Features

Help screen user game play functionality

QuizHelpActivity class help screen

User help text scroll

User Question suggest

Figure 6.4 Help screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
1.3.4. Defining Scores Screen Features

screen user game scores functionality

QuizScoresActivity class screen

Top score

user game screen score

Figure 6.5 scores screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
1.3.5. Defining Settings Screen Features

screen user game settings edit save game

settings user name and other important features functionality

QuizSettingActivity class screen

User game settings

User

Figure 6.6 basic settings screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
1.3.6. Defining Game Screen Features

screen trivia quiz display functionality QuizGameActivity class

screen

Yes/no questions

Input handle score state

User scores screen

Figure 6.7 game screen

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
2. Implementing an Application Prototype

1. Android project create

2. Application resources strings graphics

3. Screen layout resource create

4. Screen java class implement (Activity class extend

5. Activity application-wide preferences create

2.1. Creating a New Android Project

Project name: BTDT

Build target: Android 2.3.3 + Google APIs (API Level 10)

Application name: Been There, Done That!

Package name: com.android.btdt

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Create activity: QuizSplashActivity

setting project create )

2.2. Adding Project Resources

Activity layout file activity name text string

application icon

2.2.1. Adding String Resources

Eclipse res\values\strings.xml hello string string

create screen string screen

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


<resources>
<string
name="app_name">Been There, Done That!</string>
<string
name="help">Help Screen</string>
<string
name="menu">Main Menu Screen</string>
<string
name="splash">Splash Screen</string>
<string
name="settings">Settings Screen</string>
<string
name="game">Game Screen</string>
<string
name="scores">Scores Screen</string>
</resources>

2.2.2. Adding Drawable Resources

Application icon 48 x 48 pixel PNG type image file create

photoshop quizicon.png drawable folder

icon.png size create

/drawable-ldpi, /drawable-mdpi, /drawable-hdpi folder size

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
(low, medium, high resolution)

refer refer android operating system

device icon version ( project

default icon )

2.2.3. Adding Layout Resources

Activity layout resurce file create main.xml splash.xml

splash.xml file (copy ) game.xml, help.xml, menu.xml,

scores.xml, settings.xml error layout TextView conrol @string/hello

string refer hello layout file

game.xml @string/hello @string/game

splash.xml file @string/splash,

@string/help, @string/menu, @string/scores, @string/settings

2.3. Implementing Application Activities

src\com.androidbook.btdt.hour6\QuizSplashActivity.java file copy file name

QuizActivity.java coding save

package com.androidbook.btdt.hour6;

import android.app.Activity;

public class QuizActivity extends Activity {


public static final String GAME_PREFERENCES = "GamePrefs";
}

2.3.1. Creating the Rest of the Application Activities

copy file name QuizMenuActivity, QuizHelpActivity,

QuizScoresActivity, QuizSettingsActivity, QuizGameActivity (copy

com.androidbook.btdt.hour6 package name right click New Class

class name )

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
file error file main.xml

splash.xml file

QuizHelpActivity.java file setContentView() method

setContentView(R.layout.help);

package com.androidbook.btdt.hour6;

import android.os.Bundle;

public class QuizHelpActivity extends QuizActivity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
}
}

QuizScoresActivity, QuizSettingsActivity, QuizMenuActivity, QuizGameActivity file

package com.androidbook.btdt.hour6;

import android.os.Bundle;

public class QuizScoresActivity extends QuizActivity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scores);
}
}

package com.androidbook.btdt.hour6;

import android.os.Bundle;

public class QuizSettingsActivity extends QuizActivity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
}
}
package com.androidbook.btdt.hour6;

import android.os.Bundle;

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
public class QuizMenuActivity extends QuizActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
}
}

package com.androidbook.btdt.hour6;

import android.os.Bundle;

public class QuizGameActivity extends QuizActivity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
}
}

2.3.2. Updating the Android Manifest File

manifest file ( ) @drawable/quizicon (

) ( ) activity

manifest file register ( ) debuggable application attribute true QuizSplashActivity

default activity activity screen Splash screen

display

2.4. Creating Application Preferences

application bastic state information and user data functionality

androids shared preferences android.content.SharedPreferences

Shared preferences application activity

base class QuizActivity.java file public static final String GAME_PREFERENCES = "GamePrefs";

subclasses (create shared

preference preference categories preference name

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
game preferences user preferences shared preference

Application shared preference

1. Activity class SharedPreferences object instance retrieve

getSharedPreferences() method

2. Preference modify SharedPreference.Editor object create

3. Editor preference

4. Editor commit() method commit

2.4.1. Saving Specific Shared Preferences

Preference key/value preference value data type

Boolean

Float

Integer

Long

String

preference save SharedPreferences object

instance editor

commit users name age preference save activity class

code

SharedPreferences settings =
getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString(UserName, JaneDoe);
prefEditor.putInt(UserAge, 22);
prefEditor.commit();

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
preference clear shared preferences editor clear() method

preference remove ( remove preference

) remove() method

2.4.2. Retrieving Shared Preferences

Editor create retrieve activity class

shared preference values retrieve code

SharedPreferences settings =
getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
if (settings.contains(UserName) == true) {
// We have a user name
String user = Settings.getString(UserName, Default);
}
(shared preferences )

3. Running the Game Prototype

debug configuration create

3.1. Creating a Debug Configuration

New eclipse project debug configuration AVD (emulator) configure

application Minimum sdk version (

application minimum sdk version AndroidManifest.xml file

<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="10"></uses-sdk>

application android API level 7 configure emulator real android

device application API level 10

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
AVD Eclipse toolbar Android Virtual Device Manager

AVD application run Eclipse

toolbar Android Virtual Device Manager click AVD select start

button click

3.2. Launching the Prototype in the Emulator

emulator AVD manager window (emulator )

eclipse Run button click (bug) click

emulator run Lunch a new Andorid Virtual Device option select OK

configure AVD

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
AVD

OK click

emulator run real device run Figure 6.8

(emulator install run )

run

Figure 6.8

Application window icon Been There, Done That!

application application

Been There, Done That! application click

default QuizSplashActivity activity TextView

title Been There, Done That! Splash Screen TextView

application framework

coding game application

( application uninstall )

project link

https://dl.dropbox.com/u/94729309/Hour6.rar

google doc Hour6

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

Implementing an Animated Splash Screen

1. Splash screen design

2. Splash screen layout

3. Animation

1. Designing the Splash Screen

main menu screen screen

screen title and version information

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
2. Implementing the Splash Screen Layout

screen TextView and Imageview control TextView text string

ImageView graphic view screen

Layout control layout control

Layout control View control attribute behavior

control control width and height android:layout_width and

android:layout_heught attribute attribute value dimension

number of pixels

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
fill_parent or wrap_content

splash screen ImageView control display TableLayout control

splash screen parent layout LinearLayout TextView,

TableLayout ( TableRow control TableRow ImageView ),

TextView

2.1. Adding New Project Resources

layout string, color and dimension resources create

splash1.png, splash2.png, splash3.png, splash4.png resolution create

res/drawable-ldpi, res/drawable-mdpi, res/drawable-hdpi

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
/res/vlues/strings.xml file String top title (Been There)

bottom title (Done That!) version information (multiple line )

13 splash string

strings.xml file

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


<resources>
<string
name="app_name">Been There, Done That!</string>
<string
name="help">Help Screen</string>
<string
name="menu">Main Menu Screen</string>
<string
name="settings">Settings Screen</string>
<string
name="game">Game Screen</string>
<string
name="scores">Scores Screen</string>
<string
name="app_logo_top">BEEN THERE</string>
<string
name="app_logo_bottom">DONE THAT!</string>
<string
name="app_version_info">Version 2.0.0\nCopyright 2011 Mamlambo\nAll Rights
Reserved.
</string>
</resources>

/res/vaules/ color.xml file color resources title text

( version text (grayish white) version text background

(deep blue) color.xml file

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


<resources>
<color

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
name="logo_color">#FFFF0F</color>
<color
name="version_color">#f0f0f0</color>
<color
name="version_bkgrd">#1a1a48</color>
</resources>

/res/vlues/dimens.xml file dimension value title font size

(48dp), version text font size (15dp), version text line spacing (3dp)

dp unit device resolution dimens.xml file

code save

2.2. Updating the Splash Screen Layout

splash.xml file control

1. LinearLayout Orientation vertical background color attribute

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">

2. TextView (TextViewTopTitle)

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/TextViewTopTitle"
android:text="@string/app_logo_top"
android:textColor="@color/logo_color"
android:layout_gravity="center_vertical|center_horizontal"
android:gravity="top|center"
android:textSize="@dimen/logo_size"></TextView>

3. TableLayout (TableLayout01)

<TableLayout
android:id="@+id/TableLayout01"
android:stretchColumns="*"
android:layout_height="wrap_content"
android:layout_width="match_parent">

4. TableLayout TableRow TableRow ImageView

<TableRow
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
android:id="@+id/TableRow01"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal">
<ImageView
android:id="@+id/ImageView2_Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash1"></ImageView>
<ImageView
android:id="@+id/ImageView2_Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash2"></ImageView>
</TableRow>
5. TableLayout TableRow TableRow ImageView

<TableRow
android:id="@+id/TableRow02" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal">
<ImageView
android:id="@+id/ImageView3_Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash3"></ImageView>
<ImageView
android:id="@+id/ImageView3_Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash4"></ImageView>
</TableRow>
6. LinearLayout TextView (TextViewBottomTitle)

<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="@+id/TextViewBottomTitle" android:text="@string/app_logo_bottom"
android:textColor="@color/logo_color"
android:gravity="center"
android:textSize="@dimen/logo_size"></TextView>

7. LinearLayout TextView (TextViewBottomVersion)

<TextView
android:id="@+id/TextViewBottomVersion"
android:text="@string/app_version_info"
android:textSize="@dimen/version_size"
android:textColor="@color/version_color"
android:background="@color/version_bkgrd"
android:layout_height="match_parent"
android:lineSpacingExtra="@dimen/version_spacing"

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
android:layout_width="match_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:gravity="center"></TextView>

splash.xml file code

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/TextViewTopTitle"
android:text="@string/app_logo_top"
android:textColor="@color/logo_color"
android:layout_gravity="center_vertical|center_horizontal"
android:gravity="top|center"
android:textSize="@dimen/logo_size"></TextView>
<TableLayout
android:id="@+id/TableLayout01"
android:stretchColumns="*"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TableRow
android:id="@+id/TableRow01"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal">
<ImageView
android:id="@+id/ImageView2_Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash1"></ImageView>
<ImageView
android:id="@+id/ImageView2_Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash2"></ImageView>
</TableRow>
<TableRow
android:id="@+id/TableRow02"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal">
<ImageView
android:id="@+id/ImageView3_Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash3"></ImageView>
<ImageView
android:id="@+id/ImageView3_Right"

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="@drawable/splash4"></ImageView>
</TableRow>
</TableLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/TextViewBottomTitle"
android:text="@string/app_logo_bottom"
android:textColor="@color/logo_color"
android:gravity="center"
android:textSize="@dimen/logo_size"></TextView>
<TextView
android:id="@+id/TextViewBottomVersion"
android:text="@string/app_version_info"
android:textSize="@dimen/version_size"
android:textColor="@color/version_color"
android:background="@color/version_bkgrd"
android:layout_height="match_parent"
android:lineSpacingExtra="@dimen/version_spacing"
android:layout_width="match_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:gravity="center"></TextView>
</LinearLayout>

save run

3. Working with Animation

splash screen animation Android platform graphics animation

support

Animated GIF images


htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Frame-by-frame animation

Tweened animation

OpenGL ES

application Tweened animation alpha (transparency), rotation, scaling,

translating (moving) animations

3.1. Adding Animations Resources

Animation create fade_in.xml, fade_in2.xml, custom_anim.xml file

/res/anim fade_in.xml file 2.5 seconds alpha value 0 (transparent) 1

(opaque) fade_in.xml file code

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


<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="2500">
</alpha>
</set>

animation top TextView control

fade_in2.xml animation file stratOffset attribute 2500

milliseconds animation 5 seconds 2.5

seconds 2.5 seconds fade ( ) 5 seconds splash screen

display fade_in2.xml file

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


<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="2500"
android:startOffset="2500">
</alpha>
</set>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
TableLayout graphics animation sequence

rotation, scaling, alpha transition custom_anim.xml file

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


<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000" />
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="2000">
</alpha>
<scale
android:pivotX="50%"
android:pivotY="50%"
android:fromXScale=".1"
android:fromYScale=".1"
android:toXScale="1.0"
android:toYScale="1.0"
android:duration="2000" />
</set>

0 360 degree rotate 2 seconds alpha value 0 1 2

seconds 10% 100% scale 2 seconds animation 2 seconds

parallel file save animation View

3.2. Animating Specific Views

Animation sequence activity class file (QuizSplashAcivity class) coding

manage application pause animation application

resume animation resume

fade_in animation title TextView (TextViewTopTitle) apply

QuizSplashAcitivty class TextView control instance create animation resource

(TextViewTopTitle) Animation object (logo1) load stratAnimation() method

TextView logo1 = (TextView) findViewById(R.id.TextViewTopTitle);

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Animation fade1 = AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo1.startAnimation(fade1);

onPause() callback animation stop clearAnimation() method

onPause() method code

@Override
protected void onPause() {
super.onPause();
// Stop the animation
TextView logo1 = (TextView) findViewById(R.id.TextViewTopTitle);
logo1.clearAnimation();
TextView logo2 = (TextView) findViewById(R.id.TextViewBottomTitle);
logo2.clearAnimation();
//stop other animations
}

3.3. Animating All View in a Layout

Animation View apply parent control child View control

apply TableLayout LayoutAnimationController

object

Animation load

LayoutAnimationController instance create

configure

layout setLayoutAnimation() method pass

- code

custom_animation load

LayoutAnimationController create

TableLayout TableRow apply

Animation spinin = AnimationUtils.loadAnimation(this, R.anim.custom_anim);


LayoutAnimationController controller = new LayoutAnimationController(spinin);
TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
for (int i = 0; i < table.getChildCount(); i++) {
TableRow row = (TableRow) table.getChildAt(i);
row.setLayoutAnimation(controller);
}
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
startAniation() method call LayoutAnimationController

LayoutAnimationController animation stop clearAnimation() method

onPause() method code

TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);


for (int i = 0; i < table.getChildCount(); i++) {
TableRow row = (TableRow) table.getChildAt(i);
row.clearAnimation();
}

3.4. Handling Animation Life Cycle Events

splash screen animation animation

QuizSplshActivity QuizMenuActivity QuizMenuActivity Intent

create Intent startActivity() method pass QuizSplashActivity

finish() method ( back button splash screen

QuizSplashActivity activity stack finish ) fade_in2

animation 5 seconds AnimationListener object create callback

start, end, repeat onAnimationEnd() method implement

AnimationListener create onAnimationEnd() callback implement

code

Animation fade2 = AnimationUtils.loadAnimation(this, R.anim.fade_in2);


fade2.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(Animation animation) {
startActivity(new Intent(QuizSplashActivity.this, QuizMenuActivity.class));
QuizSplashActivity.this.finish();
}
});

emulator or real device (handset) run splash screen animation

main menu main menu

Example project code hour7

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Android Application ( )

Implementing the Main Menu Screen

4. Main menu screen design

5. Main menu screen layout implement

6. ListViews controls

7. menu types

1. Designing the Menu Screen

screen application screen user option

play the game, review the help, configure the settings, view the high scores

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
option button

button click listen screen display

play the game button click game play screen option

button button ListView control

List View option option screen scroll

Menu background image ListView control custom selection graphic

User list option click activity (screen) display

1.1. Determining Main Menu Screen Layout Requirements

QuizMenuActivity /res/layout/menu.xml layout file header,

ListView control, ImageView control

1.2. Designing the Screen Header with RelativeLayout


htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Header screen title TextView control display TextView control

RelativeLayout

RelativeLayout child view parent layout or other child view control

header RelativeLayout control

child layout

ImageView control (parent control top left )

TextView control (parent control top center )

ImageView control (parent control top right )

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<ImageView
android:id="@+id/ImageView_MenuHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"></ImageView>
<TextView
android:id="@+id/TextView01"
android:layout_height="wrap_content"
android:text="@string/menu"
android:textSize="@dimen/screen_title_size"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:layout_width="wrap_content"
android:layout_gravity="fill_horizontal|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:shadowColor="@android:color/white"
android:textColor="@color/title_color"></TextView>
<ImageView
android:id="@+id/ImageView_MenuHeader2"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_gravity="right|center_vertical"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"></ImageView>
</RelativeLayout>

1.3. Designing the ListView Control

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
ListView control View object custom divider selector

<ListView
android:layout_height="wrap_content"
android:id="@+id/ListView_Menu"
android:layout_width="match_parent"
android:divider="@drawable/divider"
android:listSelector="@drawable/selector"
android:layout_centerHorizontal="true"
android:layout_below="@+id/RelativeLayout01"></ListView>

1.4. Finishing Touches for the Main Menu Layout Design

ListView control ImageView

<ImageView
android:id="@+id/ImageView_MenuBottom"
android:src="@drawable/half"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerInside"></ImageView>
main menu screen layout design

RelativeLayout

o RelativeLayout

ImageView

TextView (Title)

ImageView

o ListView

Item(0): TextView(Play Game)

Item(1): TextView(View Scores)

Item(2): TextView(Settings)

Item(3): TextView(Help)

o ImageView

menu.xml file
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bkgrnd">
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<ImageView
android:id="@+id/ImageView_MenuHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"></ImageView>
<TextView
android:id="@+id/TextView01"
android:layout_height="wrap_content"
android:text="@string/menu"
android:textSize="@dimen/screen_title_size"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:layout_width="wrap_content"
android:layout_gravity="fill_horizontal|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:shadowColor="@android:color/white"
android:textColor="@color/title_color"></TextView>
<ImageView
android:id="@+id/ImageView_MenuHeader2"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_gravity="right|center_vertical"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"></ImageView>
</RelativeLayout>
<ListView
android:layout_height="wrap_content"
android:id="@+id/ListView_Menu"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:layout_below="@+id/RelativeLayout01"></ListView>
<ImageView
android:id="@+id/ImageView_MenuBottom"
android:src="@drawable/half"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerInside"></ImageView>
</RelativeLayout>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
2. Implementing the Main Menu Screen Layout

Project resurce

2.1. Adding New Project Resources

Layout drawable, string, color, dimension resource

/res/drawable bkgrnd.png, divider.png, half.png, slector.png bkgrnd.png background image

(RelativeLayout divider.png and selector.png custom divider and selector

(ListView control half.png screen (ImageView

/res/values/string.xml string

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


<resources>
<string
name="app_name">Been There, Done That!</string>
<string
name="help">Help Screen</string>
<string
name="settings">Settings Screen</string>
<string
name="game">Game Screen</string>
<string
name="scores">Scores Screen</string>
<string
name="app_logo_top">BEEN THERE</string>
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
<string
name="app_logo_bottom">DONE THAT!</string>
<string
name="app_version_info">Version 2.0.0\nCopyright 2011 Mamlambo\nAll Rights
Reserved.
</string>
<string
name="menu">MAIN MENU</string>
<string
name="menu_item_settings">Settings</string>
<string
name="menu_item_play">Play Game</string>
<string
name="menu_item_scores">View Scores</string>
<string
name="menu_item_help">Help</string>
</resources>

/res/values/colors.xml Color resource

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


<resources>
<color
name="logo_color">#FFFF0F</color>
<color
name="version_color">#f0f0f0</color>
<color
name="version_bkgrd">#1a1a48</color>
<color
name="title_color">#f0f0f0</color>
<color
name="title_glow">#F00</color>
<color
name="menu_color">#FFFF0F</color>
<color
name="menu_glow">#F00</color>
</resources>

/res/values/dimens.xml dimension

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


<resources>
<dimen
name="logo_size">48dp</dimen>
<dimen
name="version_size">15dp</dimen>
<dimen
name="version_spacing">3dp</dimen>
<dimen
name="screen_title_size">40dp</dimen>
<dimen
name="menu_item_size">34dp</dimen>
</resources>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
2.2. Updating the Main Menu Screen Layout Files

Master layout file menu.xml screen layout ListView

control layout file create

2.2.1. Adding the ListView Template Layout

ListView control item item layout template

/res/layout/menu_item.xml file

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


<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:textSize="@dimen/menu_item_size"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:shadowRadius="5"
android:gravity="center"
android:textColor="@color/menu_color"
android:shadowColor="@color/menu_glow"
android:shadowDy="3"
android:shadowDx="3" />

3. Working with the ListView Control

QuizMenuActivity.java file ListView control

ListView control item click listen

user click item screen display Play Game item click Game play

screen display

3.1. Filling a ListView Control

ListView item QuizMenuActivity class onCreate() method code

findViewById() method ListView

ListView menuList = (ListView) findViewById(R.id.ListView_Menu);

resource string load

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
String[] items = { getResources().getString(R.string.menu_item_play),
getResources().getString(R.string.menu_item_scores),
getResources().getString(R.string.menu_item_settings),
getResources().getString(R.string.menu_item_help) };

ListView control data data layout template

(menu_item.xml) map map adapter data type

application ArrayAdapter

ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, R.layout.menu_item, items);


menuList.setAdapter(adapt);

setAdapter() method call ListView control data adapter

menuList.setAdapter(adapt);

QuizMenuAcivity.java file

package com.androidbook.btdt.hour8;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.TextView;

public class QuizMenuActivity extends QuizActivity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.menu);

ListView menuList = (ListView) findViewById(R.id.ListView_Menu);

String[] items = { getResources().getString(R.string.menu_item_play),

getResources().getString(R.string.menu_item_scores),
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
getResources().getString(R.string.menu_item_settings),

getResources().getString(R.string.menu_item_help) };

ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, R.layout.menu_item, items);

menuList.setAdapter(adapt);

file save run splash screen main menu screen

menu item click

3.2. Listening for ListView Events

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
ListView item click listen respond listen

setOnItemClickListener() method respond onItemClick() method implement

item click application activity (screen) launch

menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long


id) {

// Note: if the list was built "by hand" the id could be used.
// As-is, though, each item has the same id

TextView textView = (TextView) itemClicked;


String strText = textView.getText().toString();

if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_play))) {
// Launch the Game Activity
startActivity(new Intent(QuizMenuActivity.this, QuizGameActivity.class));
} else if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_help))) {
// Launch the Help Activity
startActivity(new Intent(QuizMenuActivity.this, QuizHelpActivity.class));
} else if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_settings))) {
// Launch the Settings Activity
startActivity(new Intent(QuizMenuActivity.this,
QuizSettingsActivity.class));
} else if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_scores))) {
// Launch the Scores Activity
startActivity(new Intent(QuizMenuActivity.this, QuizScoresActivity.class));
}

}
});
OnItemClick() method item click information pass

QuizMenuActivity.java file

menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long


id) {

// Note: if the list was built "by hand" the id could be used.
// As-is, though, each item has the same id

TextView textView = (TextView) itemClicked;


String strText = textView.getText().toString();

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_play))) {
// Launch the Game Activity
startActivity(new Intent(QuizMenuActivity.this, QuizGameActivity.class));
} else if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_help))) {
// Launch the Help Activity
startActivity(new Intent(QuizMenuActivity.this, QuizHelpActivity.class));
} else if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_settings))) {
// Launch the Settings Activity
startActivity(new Intent(QuizMenuActivity.this,
QuizSettingsActivity.class));
} else if
(strText.equalsIgnoreCase(getResources().getString(R.string.menu_item_scores))) {
// Launch the Scores Activity
startActivity(new Intent(QuizMenuActivity.this, QuizScoresActivity.class));
}

}
});
run menu item click screen

3.3. Customizing ListView Control Characteristics

ListView custom divider and selection picture

3.3.1. Adding a Custom Divider

Divider ListView item divider attribute color or drawable graphic

resource color item horizontal line

drawable graphic resource item graphic

item item divider

ListView control divider menu.xml file ListView control divider attribute

@drawable/divider

<ListView
android:layout_height="wrap_content"
android:id="@+id/ListView_Menu"
android:layout_width="match_parent"
android:divider="@drawable/divider"
android:layout_centerHorizontal="true"
android:layout_below="@+id/RelativeLayout01"></ListView>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
3.3.2. Adding a Custom Selector

List item item select ListView selector

listSelector attribute default

Selector menu.xml file ListView control listSelector attribute

@drawable/selector

<ListView
android:layout_height="wrap_content"
android:id="@+id/ListView_Menu"
android:layout_width="match_parent"
android:divider="@drawable/divider"
android:listSelector="@drawable/selector"
android:layout_centerHorizontal="true"
android:layout_below="@+id/RelativeLayout01"></ListView>

save run divider selector

4. Working with Other Menu Types

Android menu type

Context menus

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
View object menu context menu

Options menus

Handset menu button click menu Options menu

4.1. Adding an Options Menu to the Game Screen

Option menu menu resources QuizGameActivtiy class

coding

4.1.1. Adding Menu Resources

/res/menu gameoptions.xml file menu resource <menu> <item>

tag item attribute

id

option menu item identify

tilte

option menu item string

icon

menu item

application option menu option Settings and Help

gameoptions.xml file

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


<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/settings_menu_item"
android:title="@string/menu_item_settings"
android:icon="@android:drawable/ic_menu_preferences"></item>
<item
android:id="@+id/help_menu_item"
android:title="@string/menu_item_help"
android:icon="@android:drawable/ic_menu_help"></item>
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
</menu>

4.1.2. Adding an Options Menu to an Activity

Option menu QuizGameActivity class QuizGameActivity class

onCreateOptionsMenu() method implement

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.gameoptions, menu);
menu.findItem(R.id.help_menu_item).setIntent(
new Intent(this, QuizHelpActivity.class));
menu.findItem(R.id.settings_menu_item).setIntent(
new Intent(this, QuizSettingsActivity.class));
return true;
}

4.1.3. Handling Options Menu Selections

User option menu item onOptionItemSelected() method

user select menu item intent activity (screen) lunch

(display)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
startActivity(item.getIntent());
return true;
}

QuizGameActivity.java file complete code

package com.androidbook.btdt.hour8;

import android.content.Intent;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

public class QuizGameActivity extends QuizActivity {

/** Called when the activity is first created. */

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.game);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

super.onCreateOptionsMenu(menu);

getMenuInflater().inflate(R.menu.gameoptions, menu);

menu.findItem(R.id.help_menu_item).setIntent(

new Intent(this, QuizHelpActivity.class));

menu.findItem(R.id.settings_menu_item).setIntent(

new Intent(this, QuizSettingsActivity.class));

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

super.onOptionsItemSelected(item);

startActivity(item.getIntent());

return true;

save run

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Example project code Hour8

Andorid Application ( )

Help Scores Screens

1. Designing and implementing the help screen


2. Working with files

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
3. Designing and implementing the scores screen
4. Designing screens with tabs
5. Working with XML

1. Designing and Implementing the Help Screen


1.1. Designing the Help Screen
screen text display scroll

Lay out design

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
1.2. Implementing the Help Screen Layout
Project new resources help.xml file

1.2.1. Adding New Project Resources


Help screen layout string, color, dimension resources text file
help screen main TextView control display text
quizhelp.txt file

Have you been there?


Have you done that?

BEEN THERE, DONE THAT! is a trivia quiz dedicated to those who love travel and adventure. By
answering a series of Yes or No questions, you gain points toward being the most well-traveled
and field-tested person on the planet. Share your experiences and compete with your friends.

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
GAME SETTINGS

<TBD>

SUPPORT INFORMATION

"Been There, Done That!" was developed by Mamlambo.

Phone: 1-800-555-1212
Email: support@mamlambo.com
Website: http://www.mamlambo.com
Address: 1060 West Addison Street, Chicago, IL 60613 (Pardon the Blues Brothers reference)
COPYRIGHT (c) 2011, Mamlambo.
All rights reserved.

quizhelp.txt file res/raw/

1.2.2. Updating the Help Screen Layout

res/layout help.xml file Help screen layout file help.xml file


xml code

LinearLayout background attribute @drawable/bkgrnd

RelativeLayout Relative layout ImageView control


TextView TextView control text attribute @string/help

RelativeLayout control TextView control id


TextView_HelpText linksClickable attribute true autoLink attribute
all phone numbers, web addtesses, email addresses and postal addresses
auto link textStyle attribute bold or italic

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bkgrnd">
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/ImageView_Header"
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"></ImageView>
<TextView
android:id="@+id/TextView01"
android:layout_height="wrap_content"
android:text="@string/help"
android:textSize="@dimen/screen_title_size"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:layout_width="wrap_content"
android:layout_gravity="fill_horizontal|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:shadowColor="@android:color/white"
android:textColor="@color/title_color"></TextView>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ImageView_Header2"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_gravity="right|center_vertical"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"></ImageView>
</RelativeLayout>
<TextView
android:id="@+id/TextView_HelpText"
android:textColor="@color/title_color"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:autoLink="all"
android:isScrollContainer="true"
android:textStyle="italic"
android:drawablePadding="@dimen/help_text_drawable_padding"
android:textColorLink="@color/logo_color"
android:linksClickable="true"
android:fadingEdgeLength="@dimen/help_text_fading"
android:fadingEdge="vertical"
android:scrollbars="vertical"
android:padding="@dimen/help_text_padding"
android:textSize="@dimen/help_text_size"
android:scrollbarStyle="outsideOverlay"
android:bufferType="spannable"></TextView>
</LinearLayout>

2. Working with Files


quizhelp.txt file QuizHelpActivity.java file quizhelp.txt
file TextView_HelpText TextView control display

2.1. Accessing Raw File Resources


htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
quizhelp.txt file data openRawResource() method

InputStream iFile = getResources().openRawResource(R.raw.quizhelp);

InputStream object lieny-by-line or byte-by-byte string


create

TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);


String strFile = inputStreamToString(iFile);
helpText.setText(strFile);

QuizHelpActivity.java file code

package com.androidbook.btdt.hour9;

import java.io.DataInputStream;

import java.io.IOException;

import java.io.InputStream;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

public class QuizHelpActivity extends QuizActivity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.help);

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
// Read raw file into string and populate TextView

InputStream iFile = getResources().openRawResource(R.raw.quizhelp);

try {

TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);

String strFile = inputStreamToString(iFile);

helpText.setText(strFile);

} catch (Exception e) {

Log.e(DEBUG_TAG, "InputStreamToString failure", e);

/**

* Converts an input stream to a string

* @param is

* The {@code InputStream} object to read from

* @return A {@code String} object representing the string for of the input

* @throws IOException

* Thrown on read failure from the input

*/

public String inputStreamToString(InputStream is) throws IOException {

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
StringBuffer sBuffer = new StringBuffer();

DataInputStream dataIO = new DataInputStream(is);

String strLine = null;

while ((strLine = dataIO.readLine()) != null) {

sBuffer.append(strLine + "\n");

dataIO.close();

is.close();

return sBuffer.toString();

save run splash screen main menu help screen


option help screen quizhelp.txt file

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Scores screen

3. Designing and Implementing the Scores Screen


3.1. Designing the Scores Screen
screen user scores score all-time-high scores
and users friends scores screen 2 users name, score and overall
ranking
Score information TextView control or ListView control

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
3.1.1. Determining Scores Screen Layout Requirements
/res/layout/scores.xml layout file screen title bar Relative
layout TabHost control tab tab all scores
friends scores

3.1.2. Adding the TabHost Control

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
3.2. Implementing the Scores Screen Layout
design implement resources
scores.xml file

3.2.1. Adding New Project Resources


scores remote server server
xml file
/res/xml/ allscores.xml and friendscores.xml file allscores.xml
scores

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


<!--
This is a mock score XML chunk
-->
<scores>
<score
username="LED"
score="12345"
rank="1" />
<score

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
username="SAC"
score="12344"
rank="2" />
<score
username="NAD"
score="12339"
rank="3" />
<score
username="ASH"
score="12335"
rank="4" />
<score
username="KPM"
score="12245"
rank="5" />
<score
username="SDB"
score="12222"
rank="6" />
<score
username="LOL"
score="11667"
rank="7" />
<score
username="AFK"
score="11345"
rank="8" />
<score
username="BRB"
score="11234"
rank="9" />
<score
username="BUG"
score="10000"
rank="10" />
<score
username="LED"
score="1234"
rank="11" />
<score
username="SAC"
score="123"
rank="12" />
<score
username="NAD"
score="122"
rank="13" />
<score
username="ASH"
score="121"
rank="14" />
<score
username="KPM"
score="21"
rank="15" />
<score
username="SDB"
score="12"

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
rank="16" />
<score
username="LOL"
score="11"
rank="17" />
<score
username="AFK"
score="5"
rank="18" />
<score
username="BRB"
score="3"
rank="19" />
<score
username="BUG"
score="1"
rank="20" />
</scores>

friendscores.xml file

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


<!--
This is a mock score XML chunk
-->
<scores>
<score
username="BAG"
score="12345"
rank="101" />
<score
username="BET"
score="12344"
rank="201" />
<score
username="SIM"
score="12339"
rank="322" />
<score
username="TUG"
score="12335"
rank="444" />
<score
username="RUG"
score="12245"
rank="555" />
<score
username="YUK"
score="12222"
rank="666" />
<score
username="YAK"
score="11667"
rank="777" />
<score
username="WAH"
score="11345"
rank="888" />
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
<score
username="FOG"
score="11234"
rank="999" />
<score
username="LUG"
score="10000"
rank="1001" />
</scores>

<scores> element child <score> element element attribute


username, score and rank

3.2.2. Updating the Scores Screen Layout

Scores screen user interface scores.xml layout file

TabHost controls design mode

XML layout mode tab emulator device

run )

Layout file update

control

LinearLayout control android:background attribute @drawable/bkgrnd

LinearLayout control control

RelativeLayout control ImageView TextView TextView

control text attribute @string/scores

RelativeLayout control TabHost control TabHost1

layout_width and layout_height attribute

TabHost control LinearLayout control orientation

attribute vertical layout_width and layout_height

LinearLayout control TabWidget control control id attribute

@android:id/tabs

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
FrameLayout control id @android:id/tabcontent

layout_width and layout_height

FrameLayout control TableLayout control Tab TableLayout

control Tab TableLayout control TableLayout

control scores display TableLayout control

TableLayout_AllScores TableLayout_FriendScores

layout_width and layout_height scores

information table column resize stretchColumns

attribute *

res/layout/xml/scores.xml file content

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bkgrnd">
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ImageView_Header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"></ImageView>
<TextView
android:id="@+id/TextView01"
android:layout_height="wrap_content"
android:text="@string/scores"
android:textSize="@dimen/screen_title_size"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:layout_width="wrap_content"
android:layout_gravity="fill_horizontal|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:shadowColor="@android:color/white"
android:textColor="@color/title_color"></TextView>

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ImageView_Header2"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_gravity="right|center_vertical"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"></ImageView>
</RelativeLayout>
<TabHost
android:id="@+id/TabHost1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:id="@+id/ScrollViewAllScores"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
<TableLayout
android:id="@+id/TableLayout_AllScores"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
</TableLayout>
</ScrollView>
<ScrollView
android:id="@+id/ScrollViewFriendScores"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
<TableLayout
android:id="@+id/TableLayout_FriendScores"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"></TableLayout>
</ScrollView>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>

4. Designing Screens with Tabs

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
QuizScoresAcitivity.java file code Tabhost control
initialize tab All Scores tab default tab

4.1. Configuring the TablHost Control


TabHost control findViewById() method retirve TabHost control
setup() method call

// Set up the tabs


TabHost host = (TabHost) findViewById(R.id.TabHost1);
host.setup();

4.2. Adding Tabs to the TabHost Control

TabHost control retrieve initialize tab configure

addTab() method All scores tab create code

// All Scores tab


TabSpec allScoresTab = host.newTabSpec("allTab");
allScoresTab.setIndicator(getResources().getString(R.string.all_scores),
getResources().getDrawable(
android.R.drawable.star_on));
allScoresTab.setContent(R.id.ScrollViewAllScores);
host.addTab(allScoresTab);

Friends scores tab code

// Friends Scores tab


TabSpec friendScoresTab = host.newTabSpec("friendsTab");
friendScoresTab.setIndicator(getResources().getString(R.string.friends_scores),
getResources().getDrawable(
android.R.drawable.star_on));
friendScoresTab.setContent(R.id.ScrollViewFriendScores);
host.addTab(friendScoresTab);

4.3. Setting the Default Tab

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
Default tab setCurrentTabByTag() method call tab
tag name pass

// Set the default tab


host.setCurrentTabByTag("allTab");

save run scores screen tab display scores


data

5. Working with XML


Android platform XML data mechanism
SAX (Simple API for XML)
XML Pull Parser
Limited DOM Level 2 core support

XML technology project tutorial


simple XML file

5.1. Retrieving XML Resources


Project resurces save XML data
(/res/xml/allscores.xml) getXML() method XmlResourceParser instance initialize

XmlResourceParser mockAllScores = getResources().getXml(R.xml.allscores);

5.2. Parsing XML Files with XmlResourceParser


<score> tag username, rank and score attributes extract
next() method while () loop

int eventType = -1;


boolean bFoundScores = false;
// Find Score records from XML
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
// Get the name of the tag (eg scores or score)
String strName = scores.getName();
if (strName.equals("score")) {
bFoundScores = true;
String scoreValue = scores.getAttributeValue(null, "score");
String scoreRank = scores.getAttributeValue(null, "rank");
String scoreUserName = scores.getAttributeValue(null, "username");
insertScoreRow(scoreTable, scoreValue, scoreRank, scoreUserName);
}

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
}
eventType = scores.next();
}

Loop START_TAG event tag name <score> tag match score data
getAttributeValue() method data extract score
TableLayout control TableRow control

QuizScoresAcitivity.java file code

package com.androidbook.btdt.hour9;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.content.res.XmlResourceParser;

import android.os.Bundle;

import android.util.Log;

import android.widget.TabHost;

import android.widget.TabHost.TabSpec;

import android.widget.TableLayout;

import android.widget.TableRow;

import android.widget.TextView;

public class QuizScoresActivity extends QuizActivity {

/** Called when the activity is first created. */

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.scores);

// Set up the tabs

TabHost host = (TabHost) findViewById(R.id.TabHost1);

host.setup();

// All Scores tab

TabSpec allScoresTab = host.newTabSpec("allTab");

allScoresTab.setIndicator(getResources().getString(R.string.all_scores), getResources().getDrawable(

android.R.drawable.star_on));

allScoresTab.setContent(R.id.ScrollViewAllScores);

host.addTab(allScoresTab);

// Friends Scores tab

TabSpec friendScoresTab = host.newTabSpec("friendsTab");

friendScoresTab.setIndicator(getResources().getString(R.string.friends_scores),
getResources().getDrawable(

android.R.drawable.star_on));

friendScoresTab.setContent(R.id.ScrollViewFriendScores);

host.addTab(friendScoresTab);

// Set the default tab

host.setCurrentTabByTag("allTab");

// Retrieve the TableLayout references


htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
TableLayout allScoresTable = (TableLayout) findViewById(R.id.TableLayout_AllScores);

TableLayout friendScoresTable = (TableLayout) findViewById(R.id.TableLayout_FriendScores);

// Give each TableLayout a yellow header row with the column names

initializeHeaderRow(allScoresTable);

initializeHeaderRow(friendScoresTable);

XmlResourceParser mockAllScores = getResources().getXml(R.xml.allscores);

XmlResourceParser mockFriendScores = getResources().getXml(R.xml.friendscores);

try {

processScores(allScoresTable, mockAllScores);

processScores(friendScoresTable, mockFriendScores);

} catch (Exception e) {

Log.e(DEBUG_TAG, "Failed to load scores", e);

/**

* Add a header {@code TableRow} to the {@code TableLayout} (styled)

* @param scoreTable

* the {@code TableLayout} that the header row will be added to

*/

private void initializeHeaderRow(TableLayout scoreTable) {

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
// Create the Table header row

TableRow headerRow = new TableRow(this);

int textColor = getResources().getColor(R.color.logo_color);

float textSize = getResources().getDimension(R.dimen.help_text_size);

addTextToRowWithValues(headerRow, getResources().getString(R.string.username), textColor,


textSize);

addTextToRowWithValues(headerRow, getResources().getString(R.string.score), textColor, textSize);

addTextToRowWithValues(headerRow, getResources().getString(R.string.rank), textColor, textSize);

scoreTable.addView(headerRow);

/**

* Churn through an XML score information and populate a {@code TableLayout}

* @param scoreTable

* The {@code TableLayout} to populate

* @param scores

* A standard {@code XmlResourceParser} containing the scores

* @throws XmlPullParserException

* Thrown on XML errors

* @throws IOException

* Thrown on IO errors reading the XML

*/
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
private void processScores(final TableLayout scoreTable, XmlResourceParser scores) throws
XmlPullParserException,

IOException {

int eventType = -1;

boolean bFoundScores = false;

// Find Score records from XML

while (eventType != XmlResourceParser.END_DOCUMENT) {

if (eventType == XmlResourceParser.START_TAG) {

// Get the name of the tag (eg scores or score)

String strName = scores.getName();

if (strName.equals("score")) {

bFoundScores = true;

String scoreValue = scores.getAttributeValue(null, "score");

String scoreRank = scores.getAttributeValue(null, "rank");

String scoreUserName = scores.getAttributeValue(null, "username");

insertScoreRow(scoreTable, scoreValue, scoreRank, scoreUserName);

eventType = scores.next();

// Handle no scores available

if (bFoundScores == false) {

final TableRow newRow = new TableRow(this);


htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
TextView noResults = new TextView(this);

noResults.setText(getResources().getString(R.string.no_scores));

newRow.addView(noResults);

scoreTable.addView(newRow);

/**

* {@code processScores()} helper method -- Inserts a new score {@code

* TableRow} in the {@code TableLayout}

* @param scoreTable

* The {@code TableLayout} to add the score to

* @param scoreValue

* The value of the score

* @param scoreRank

* The ranking of the score

* @param scoreUserName

* The user who made the score

*/

private void insertScoreRow(final TableLayout scoreTable, String scoreValue, String scoreRank, String
scoreUserName) {

final TableRow newRow = new TableRow(this);


htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
int textColor = getResources().getColor(R.color.title_color);

float textSize = getResources().getDimension(R.dimen.help_text_size);

addTextToRowWithValues(newRow, scoreUserName, textColor, textSize);

addTextToRowWithValues(newRow, scoreValue, textColor, textSize);

addTextToRowWithValues(newRow, scoreRank, textColor, textSize);

scoreTable.addView(newRow);

/**

* {@code insertScoreRow()} helper method -- Populate a {@code TableRow} with

* three columns of {@code TextView} data (styled)

* @param tableRow

* The {@code TableRow} the text is being added to

* @param text

* The text to add

* @param textColor

* The color to make the text

* @param textSize

* The size to make the text

*/

private void addTextToRowWithValues(final TableRow tableRow, String text, int textColor, float textSize)
{
htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin
TextView textView = new TextView(this);

textView.setTextSize(textSize);

textView.setTextColor(textColor);

textView.setText(text);

tableRow.addView(textView);

5.3. Applying Finishing Touches to the Scores Screen


Run scores screen tab scores data

Complete source code


http://www.mediafire.com/?lm1cbc6s6d53uay

htarhtarlwin.blogspot.com
www.facebook.com/htarhtarlwintun
www.facebook.com/groups/htarhtarlwin

Вам также может понравиться