TM
Java
Firhat Hidayat, S.Kom.
a nd A
p
o
h
s
TM Work
d
i
o
r
d
n
Module-by-Module Overview
! Module 1 : Introduction Java
Module 2 : Object Oriented
Module 3 : Variables
Module 4 : How Object Behave
Module 5 : Core Concept Android
! Module 6 : Activities
Module 1
Introduction Java
The Way Java Work
Code Structure in Java
Anatomy of Class
public class MyFirstApp {
public static void main (String[] args) {
System.out.println(Java and Android workshop);
}
}
The main() Method
public static void main (String[] args) {
// your code goes here;
}
Looping
! Java has three standard looping constructs : while, dowhile, and for
! The key to a loop is the conditional test that result in a
boolean value
! You can do a simple boolean test by checking the value of
a variable, using a comparison operator including :
< (less than)
>(greater than)
== (equality)
Int x = 4; // assign 4 to x
while (x>3) {
//loop code will run because x is greater than 3
x = x-1;
}
Int z = 27;
while (z == 17) {
//loop code will not run because z is not equal to 17
}
Conditional Branching (if test)
class IfTest {
public static void main(String[] args){
int x = 3;
if(x==3) {
System.out.println(x must be 3);
}
System.out.println(This runs no matter what);
}
}
Coding The 99 coin on my pocket App
Public class Coin {
public static void main(String[] args){
int coinNum = 99;
String word = coins;
while (coinNum > 0) {
if (coinNum == 1) {
word = coin;
}
System.out.println(coinNum + + word + + of coin in the pocket);
System.out.println(take one out);
coinNum = coinNum-1;
if (coinNum==0) {
System.out.println(no more coin in the pocket);
}
}
}
}
Compiler Vs JVM
Java Virtual Machine
Compiler
Makes a program run
Makes a bytecode file that
could run by JVM
Stop anything that would
never could never
succeed at runtime
Module 2
Object Oriented
Object Oriented vs Procedural
The Good Thing About OO toward Procedural:
Not messing around with code that have already tested, just to add new
feature
The data and the method that operate on that data are together in one
class
Reusing code in other applications
Inheritance
Square
rotate ()
palySound ()
Shape
rotate ()
palySound ()
Circle
rotate ()
palySound ()
Triangle
Amoeba
rotate ()
palySound ()
rotate ()
palySound ()
Shape
superclass
rotate ()
palySound ()
subclasses
Square
Circle
Triangle
Amoeba
Overriding Method
Shape
rotate ()
palySound ()
Square
Circle
Triangle
Amoeba
rotate () {
//amoeba specific
rotate method}
playsound () {
//amoeba specific
sound code}
Class Structure
When you design a class, think about the object that will be created from that
Class type. Think about :
things the object knows
things the object does
Things an object knows about itself are called instance variables
Things an object can do are called methods
Shopping Cart
Button
cartContents
knows
label
color
knows
addToCart()
removeFromCart()
checkOut()
does
setColor()
setLabel()
dePress()
unDePress()
does
Using main()
GuessGame
GameLauncher
main(String[] args)
p1
p2
p3
startGame()
public class GuessGame {
Player p1;
Player p2;
Player p3;
public void startGame() {
p1=new Player();
p2=new Player();
p3=new Player();
Player
number
guess()
int guessp1=0;
int guessp2=0;
int guessp3=0;
boolean p1isRight=false;
boolean p2isRight=false;
boolean p3isRight=false;
int targetNumber=(int)(Math.random()*10);
System.out.println(Im thinking of a number between 0 and 9);
while(true){
System.out.println(Number to guess is +targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1=p1.number;
System.out.println(Player one guessed +guessp1);
guessp2=p2.number;
System.out.println(Player two guessed +guessp2);
guessp3=p3.number;
System.out.println(Player three guessed +guessp3);
if(uessp1==targetNumber){
p1isRight=true;
}
if(uessp2==targetNumber){
p2isRight=true;
}
if(uessp3==targetNumber){
p3isRight=true;
}
if(p1isRight||p2isRight||p3isRight){
System.out.println(We have a winner!);
System.out.println(Player one got it right? +p1isRight);
System.out.println(Player two got it right? +p2isRight);
System.out.println(Player three got it right? +p3isRight);
System.out.println(game is over);
break;
}else{
System.out.println(Players will have to try again);
}
}
}
}
public class Player{
int number=0;
public void guess(){
number=(int)(Math.random()*10);
System.out.println(Im guessing +number);
}
public class GameLauncher{
public static void main(String[] args){
GuessGame game=new GuessGame();
game.startGame();
}
}
Module 3
Variables
Declaring a Variable
Variables come in two flavors : primitive and object reference. Primitives
hold fundamental values including integers, booleans, and floating point
numbers. Object reference hold reference to object.
Regardless the type, there is two declaration rules:
variables must have a type
variables must have a name
int count;
type
name
Primitive Types
Type
Bit Depth
boolean and char
boolean (JVM-specific)
char
16 bits
numeric (all are signed)
integer
byte
8 bits
short
16 bits
int
32 bits
long
64 bits
floating point
float
32 bits
double
64 bits
Value Range
true or false
0 to 65535
128 to 127
-32768 to 32767
-2147483648 to 2147483647
-huge to huge
varies
varies
primitive declarations with assignments:
int x;
x=234;
byte b=89;
boolean isFun=true;
double d=3456.98
char c=f
int z=x;
boolean isPunkRock;
isPunkRock=false;
boolean powerOn;
powerOn=isFun;
long big=3456789;
float f=32.5f;
Java Keyword
A class, method, or variable can be named according to the following
rules:
it must start with a letter, underscore (_), or dollar sign($). You cant start
a name with a number
After the first character, you can use numbers as well
it can be anything you like, subject to those two rules, just so long as it
isnt one of Javas reserved words.
Java reserved words :
boolean
protected
else
class
catch
byte
abstract
do
extends
finally
char
final
while
implements
try
double
native
switch
import
throw
float
static
case
instanceof
throws
int
stictfp
default
interface
return
long
synchronized
for
new
void
short
transient
break
package
const
public
volatile
continue
super
goto
private
if
assert
this
enum
Reference Variable
An object reference variable holds bits that represent a way to access an
object
It doesnt hold the object itself, but it holds something like a pointer. Or
an address. Except, in Java we dont really know what is inside a reference
variable. We do know that whatever it is, it represents one and only one
object. And the JVM knows how to use the reference to get to the object
Object Declaration and Assignment
The three steps of object declaration, creation, and assignment
1
3
Dog myDog = new Dog();
1. Declare a reference variable
Dog myDog = new Dog();
2. Create an object
Dog myDog = new Dog();
2. Link the object and the reference
Dog myDog = new Dog();
Object on the Garbage-Collectible Heap
Book b =new Book();
Book c = new Book();
1
b
Book object
Book
2
Book object
garbage collectible heap
c
Book
1
Book d = c;
Book object
Book
2
Book object
garbage collectible heap
c
Book
d
Book
1
c = b;
Book object
Book
2
Book object
garbage collectible heap
c
d
Book
Book
b = null;
Book object
Book
2
Book object
garbage collectible heap
c
Book
d
Book
Arrays
1. Declare an int array variable
int[] nums;
2. Create a new int array with a length of 7,
and assign it to the previously declared int[]
variable nums
nums=new int[7];
3. Give each element in the array an int value
nums[0]=6;
nums[1]=19;
nums[2]=44;
nums[3]=42;
nums[4]=10;
nums[5]=20;
nums[6]=1;
nums
int[]
0 1 2 3 4 5 6
int int int int int int int
int array object (int[])
make an array of Dogs
1. Declare a Dog array variable
Dog[] pets;
2. Create a new Dog array with a length of 7,
and assign it to the previously declared Dog[]
variable pets
pets=new Dog[7];
3. Give each element in the array a Dog reference
pets[0]=new Dog();
pets[1]=new Dog();
Dog object
Dog object
Dog Dog Dog Dpg Dog Dog Dog
nums
int[]
Dog array object (Dog[])
Module 4
How Object Behave
Method Use Object State
Every instance of a particular class has the same method, but the
methods can behave differently based on the value of the instance
variables.
Song
instance
variables
(state)
method
(behaviour)
void play(){
soundPlayer.playSound(title);
}
title
artist
knows
setTitle()
setArtist()
play()
does
Method Use Object State
Every instance of a particular class has the same method, but the
methods can behave differently based on the value of the instance
variables.
Song
instance
variables
(state)
method
(behaviour)
void play(){
soundPlayer.playSound(title);
}
title
artist
knows
setTitle()
setArtist()
play()
does
four instances of class Song
My Way
Sinatra
Darkstar
Grateful
Dead
My Way
Sex Pistols
Sing
Travis
Song t2=new Song();
t2.setArtist(Travis);
t2.setTitle(Sing);
Song s3=new Song();
s3.setArtist(Sex Pistols);
s3.setTitle(My Way);
t2
s3
Song
Song
t2.play();
Calling play() on this instance
will cause Sing to play
s3.play();
Calling play() on this instance
will cause My Way to play
Method Arguments and Return Types
Arguments are the things you pass into the method. And a parameter is
nothing more than a local variable. A variable with a type and a name,
that can be used inside the body of the method.
If method takes a parameter, you must pass it something. And that
something must be a value of the appropriate type.
1. call the bark method on the Dog reference,
and pass in the value 3 (as the argument to the method)
parameter
void bark(int numOfBarks){
while(numOfBarks > 0){
System.out.println(ruff);
numOfBarks = numOfBarks - 1;
}
}
Dog d = new Dog();
d.bark(3);
argument
2. The bits representing the int
value 3 are delivered into the
bark method
3. The bits land in the numOfBarks
parameter (an int-sized variable)
4. Use the num OfBarks parameter
as a variable in the method code.
if you declare a method to return a value, you must return a value of the declared
type.
int theSecret = life.giveSecret();
these type
must match
int giveSecret() {
return 42;
}
Pass-by-Value
int x = 7
1. Declare an int variable and assign it the value 7. The bit
pattern for 7 goes into the variable named x.
x
int
void go(int z){ }
2. Declare a method with an int parameter named z.
int
copy of x
3. Call the go() method, passing the variable x as the
argument. The bits in x are copied, and the copy
lands in z.
int
int
foo.go(x);
void go(int z){ }
x and z arent
connected
x
int
4. Change the value of z inside the method. The
value of x doesnt change. The argument passed
to the z parameter was only a copy of x.
int
void go(int z){
z = 0;
}
Getter and Setter
class ElectricGuitar{
String brand;
int numOfPickups;
boolean rockStarUseIt;
String getBrand(){
return brand;
}
void setBrand(String aBrand){
brand = aBrand
}
int getNumOfPickups(){
return numOfPickUps;
}
void setNumOfPickUps(int num){
numOfPickUps=num;
}
boolean getRockStarUseIt(){
return rockStarUseIt;
}
void setRockStarUseIt(boolean yesOrNo){
rockStarUseIt = yesOrNo;
}
}
ElectricGuitar
brand
numOfPickups
rockStarUseIt
getBrand()
setBrand()
getNumOfPickups()
setNumOfPickups()
getRockStarUseIt()
setRockStarUseIt()
Encapsulations
Encapsulation puts a force-fields around class instance variables, so nobody can
set them with an inappropriate values.
Heres an encapsulation starter rule of thumb : mark your instance variables
private and provide public getters.
class GoodDog{
private int size;
public int getSize(){
return size;
}
public void setSize(int s){
size = s;
}
void bark(){
if (size > 60){
System.out.println(Woof! Woof!);
} else if (size > 14) {
System.out.println(Ruff! Ruff!);
}
GoodDog
size
getSize()
setSize()
bark()
else {
System.out.println(Yip! Yip!);
}
}
}
class GoodDogTestDrive {
public static void main(String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System .out.println(Dog one : +one.getSize());
System .out.println(Dog two : +two.getSize());
one.bark();
two.bark();
}
}
Using References in An Array
1. Declare and create a Dog array,
to hold 7 Dog references.
Dog[] pets;
Pets = new Dog[7];
0 1
2 3
4
5 6
Dog Dog Dog Dog Dog Dog Dog
Dog array object (Dog[])
pets
Dog[]
30
2. Create two new Dog objects, and
assign them to the first two array
elements.
pets[0] = new Dog();
pets[1] = new Dog();
3. Call methods on the two Dog
objects.
pets[0].setSize(30);
int x = pets[0].getSize();
pets[1].setSize(8);
size
size
Dog Object
Dog Object
0 1
2 3
4
5 6
Dog Dog Dog Dog Dog Dog Dog
Dog array object (Dog[])
pets
Dog[]
Module 5
Core Concepts
The Big Picture
! Activities :
You can think of an Activity as being the Android analogue for the
window or dialog in a desktop application.
! Content Providers :
Content providers provide a level of abstraction for any data stored
on the device that is accessible by multiple applications.
! Intents :
Intents are system messages, running around the inside of the
device, notifying applications of various events, from hardware state
changes (e.g., an SD card was inserted), to incoming data (e.g., an
SMS message arrived), to application events (e.g., your activity was
launched from the devices main menu).
! Services :
Activities, content providers, and intent receivers are all short-lived
and can be shut down at any time. Services, on the other hand, are
designed to keep running, if needed, independent of any activity.
Android comes with a number of
features to help you develop
applications :
! Storage
! Network
! Multimedia
! GPS
! Phone Service
Project
Structure
Root Contents :
! AndroidManifest.xml , an XML file describing the
application being built and what componentsactivities,
services, etc.are being supplied by that application
! build.xml, an Ant script for compiling the application and
installing it on the device
! default.properties, a property file used by the Ant build
script
! bin/ holds the application once it is compiled
! libs/ holds any third-party Java JARs your application
requires
! src/ holds the Java source code for the application
! res/ holds resources, such as icons, GUI layouts, and the
like, that get packaged with the compiled Java in the
application
! assets/ holds other static files you wish packaged with the
application for deployment onto the device
Some of the subdirectories you will find or create
under res/ include :
res/drawable/ for images (PNG, JPEG, etc.)
res/layout/ for XML-based UI layout specifications
res/menu/ for XML-based menu specifications
res/raw/ for general-purpose files (e.g., a CSV file
of account information) res/values/ for strings,
dimensions, and the like
res/xml/ for other general-purpose XML files you
wish to ship
Inside the
Manifest
! The root of all manifest files is a manifest element:
! <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.search">
...
</manifest>
! Underneath the manifest element, you will find the following:
uses-permission elements to indicate what permissions your application will
need in order to function properly.
permission elements to declare permissions that activities or services might
require other applications hold in order to use your applications data or logic.
instrumentation elements to indicate code that should be invoked on key
system events, such as starting up activities, for the purposes of logging or
monitoring.
uses-library elements to hook in optional Android components, such as
mapping services
Possibly a uses-sdk element to indicate what version of the Android SDK the
application was built for.
An application element defining the guts of the application that the manifest
describes.
! <manifest xmlns:android="http://schemas.android.com/
apk/res/android"
package="com.commonsware.android.skeleton">
! <application>
<activity android:name=".Now" android:label="Now">
! <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
! </intent-filter> </activity>
! </application> </manifest>
Module 6
Activities
Creating a Skeleton Application
(select File New Project, then choose Android Android Project)
package com.commonsware.android.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;
@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());
}
Using XML-Based Layout
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button"
android:text=""
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
package com.commonsware.android.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;
@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());
}
}
Employing Basic Widgets
Labels
The simplest widget is the label, referred to in Android as a TextView.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You were expecting something profound?"
/>
Images
The simplest widget is the label, referred to in Android as a TextView.
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/icon"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:src="@drawable/molecule"/>
Fields
The simplest widget is the label, referred to in Android as a TextView.
<?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"
/>
package com.commonsware.android.basic;
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");
}
}
Check Box
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This checkbox is: unchecked" />
public class CheckBoxDemo extends Activity
implements CompoundButton.OnCheckedChangeListener {
CheckBox cb;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cb.setText("This checkbox is: checked");
}
else {
cb.setText("This checkbox is: unchecked");
}
}
}
Radio Button
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RadioButton android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rock" />
<RadioButton android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scissors" />
<RadioButton android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paper" />
</RadioGroup>
Working with Containers
Linear Layout
LinearLayout is a box modelwidgets or child containers are lined up in a
column or row, one after the next.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RadioGroup android:id="@+id/orientation"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5px">
<RadioButton
android:id="@+id/horizontal"
android:text="horizontal" />
<RadioButton
android:id="@+id/vertical"
android:text="vertical" />
</RadioGroup>
<RadioGroup android:id="@+id/gravity"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px">
<RadioButton
android:id="@+id/left"
android:text="left" />
<RadioButton
android:id="@+id/center"
android:text="center" />
<RadioButton
android:id="@+id/right"
android:text="right" />
</RadioGroup>
</LinearLayout>
package com.commonsware.android.containers;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.text.TextWatcher;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.EditText;
public class LinearLayoutDemo extends Activity implements
RadioGroup.OnCheckedChangeListener {
RadioGroup orientation;
RadioGroup gravity;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
orientation=(RadioGroup)findViewById(R.id.orientation);
orientation.setOnCheckedChangeListener(this);
gravity=(RadioGroup)findViewById(R.id.gravity);
gravity.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (group==orientation) {
if (checkedId==R.id.horizontal) {
orientation.setOrientation(LinearLayout.HORIZONTAL);
} else {
orientation.setOrientation(LinearLayout.VERTICAL);
}
}
else if (group==gravity) {
if (checkedId==R.id.left) {
gravity.setGravity(Gravity.LEFT);
} else if (checkedId==R.id.center) {
gravity.setGravity(Gravity.CENTER_HORIZONTAL);
}
else if (checkedId==R.id.right) {
gravity.setGravity(Gravity.RIGHT);
}
}
}
Relative Layout
RelativeLayout, as the name suggests, lays out widgets based upon their
relationship to other widgets in the container and in the parent container.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px">
<TextView android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="URL:"
android:paddingTop="15px"/>
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/label"
android:layout_alignBaseline="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignRight="@id/entry"
android:text="OK" />
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>
Table Layout
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="URL:" />
<EditText android:id="@+id/entry"
android:layout_span="3"/>
</TableRow>
<View
android:layout_height="2px"
android:background="#0000FF" />
<TableRow>
<Button android:id="@+id/cancel"
android:layout_column="2"
android:text="Cancel" />
<Button android:id="@+id/ok"
android:text="OK" />
</TableRow>
</TableLayout>
Scroll View
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="0">
<TableRow>
<View
android:layout_height="80px"
android:background="#000000"/>
<TextView android:text="#000000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#440000" />
<TextView android:text="#440000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#884400" />
<TextView android:text="#884400"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#aa8844" />
<TextView android:text="#aa8844"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffaa88" />
<TextView android:text="#ffaa88"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffaa" />
<TextView android:text="#ffffaa"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffff" />
<TextView android:text="#ffffff"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
</TableLayout>
</ScrollView>
Using Selection Widgets
List
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
public class ListViewDemo extends ListActivity {
TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent,
View v, int position, long id) {
selection.setText(items[position]);
}
}
Spin
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
/>
</LinearLayout>
public class SpinnerDemo extends Activity
implements AdapterView.OnItemSelectedListener {
TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
Spinner spin=(Spinner)findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
selection.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
}
Grid
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<GridView
android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="35px"
android:horizontalSpacing="5px"
android:numColumns="auto_fit"
android:columnWidth="100px"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</LinearLayout>
public class GridDemo extends Activity
implements AdapterView.OnItemSelectedListener {
TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
GridView g=(GridView) findViewById(R.id.grid);
g.setAdapter(new FunnyLookingAdapter(this,
android.R.layout.simple_list_item_1,
items));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
selection.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
private class FunnyLookingAdapter extends ArrayAdapter {
Context ctxt;
FunnyLookingAdapter(Context ctxt, int resource,
String[] items) {
super(ctxt, resource, items);
this.ctxt=ctxt;
}
public View getView(int position, View convertView,
ViewGroup parent) {
TextView label=(TextView)convertView;
if (convertView==null) {
convertView=new TextView(ctxt);
label=(TextView)convertView;
}
label.setText(items[position]);
return(convertView);
}
}
}
Fields
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<AutoCompleteTextView android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="3"/>
</LinearLayout>
public class AutoCompleteDemo extends Activity
implements TextWatcher {
TextView selection;
AutoCompleteTextView edit;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer",
"adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu",
"aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
edit=(AutoCompleteTextView)findViewById(R.id.edit);
edit.addTextChangedListener(this);
edit.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, items));
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
selection.setText(edit.getText());
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// needed for interface, but not used
}
public void afterTextChanged(Editable s) {
// needed for interface, but not used
}
}
Applying Menus
Hardcode
public class MenuDemo extends ListActivity {
TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
public static final int EIGHT_ID = Menu.FIRST+1;
public static final int SIXTEEN_ID = Menu.FIRST+2;
public static final int TWENTY_FOUR_ID = Menu.FIRST+3;
public static final int TWO_ID = Menu.FIRST+4;
public static final int THIRTY_TWO_ID = Menu.FIRST+5;
public static final int FORTY_ID = Menu.FIRST+6;
public static final int ONE_ID = Menu.FIRST+7;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
selection=(TextView)findViewById(R.id.selection);
registerForContextMenu(getListView());
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
selection.setText(items[position]);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
populateMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) ||
super.onOptionsItemSelected(item));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return(applyMenuChoice(item) ||
super.onContextItemSelected(item));
}
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "1 Pixel");
menu.add(Menu.NONE, TWO_ID, Menu.NONE, "2 Pixels");
menu.add(Menu.NONE, EIGHT_ID, Menu.NONE, "8 Pixels");
menu.add(Menu.NONE, SIXTEEN_ID, Menu.NONE, "16 Pixels");
menu.add(Menu.NONE, TWENTY_FOUR_ID, Menu.NONE, "24 Pixels");
menu.add(Menu.NONE, THIRTY_TWO_ID, Menu.NONE, "32 Pixels");
menu.add(Menu.NONE, FORTY_ID, Menu.NONE, "40 Pixels");
}
private boolean applyMenuChoice(MenuItem item) {
switch (item.getItemId()) {
case ONE_ID:
getListView().setDividerHeight(1);
return(true);
case EIGHT_ID:
getListView().setDividerHeight(8);
return(true);
case SIXTEEN_ID:
getListView().setDividerHeight(16);
return(true);
case TWENTY_FOUR_ID:
getListView().setDividerHeight(24);
return(true);
case TWO_ID:
getListView().setDividerHeight(2);
return(true);
case THIRTY_TWO_ID:
getListView().setDividerHeight(32);
return(true);
case FORTY_ID:
getListView().setDividerHeight(40);
return(true);
}
return(false);
}
}
XML Structure
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/close"
android:title="Close"
android:orderInCategory="3"
android:icon="@drawable/eject" />
<item android:id="@+id/no_icon"
android:orderInCategory="2"
android:title="Sans Icon" />
<item android:id="@+id/disabled"
android:orderInCategory="4"
android:enabled="false"
android:title="Disabled" />
<group android:id="@+id/other_stuff"
android:menuCategory="secondary"
android:visible="false">
<item android:id="@+id/later"
android:orderInCategory="0"
android:title="2nd-To-Last" />
<item android:id="@+id/last"
android:orderInCategory="1"
android:title="Last" />
</group>
<item android:id="@+id/submenu"
android:orderInCategory="3"
android:title="A Submenu">
<menu>
<item android:id="@+id/non_ghost"
android:title="Non-Ghost"
android:visible="true"
android:alphabeticShortcut="n" />
<item android:id="@+id/ghost"
android:title="A Ghost"
android:visible="false"
android:alphabeticShortcut="g" />
</menu>
</item>
</menu>
Add this method to the Activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
theMenu=menu;
new MenuInflater(getApplication()).inflate(R.menu.sample, menu);
return(super.onCreateOptionsMenu(menu));
}