10/4/2011
1
Ad id
11
A
n
d
ro
id
DialogBoxes
AlertDialog &ToastWidgets
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
AndroidDevelopers
/>11.Android–UI–TheDialogBox
TheDialogBox
Androidprovidestwoprimitiveformsof
dialogboxes:
1. AlertDialog boxes,and
2. Toastcontrols
22
10/4/2011
2
11.Android–UI–TheDialogBox
TheAlertDialog
TheAlertDialog isanalmost modal screen
that
(1) presentsabriefmessagetotheuser
typicallyshownasasmallfloating
windowthatpartiallyobscuresthe
underlyingview,and
(2) collectsasimpleanswer(usuallyby
333
clickinganoptionbutton).
Note:
Afullymodal viewremainsonthescreenwaitingforuser’sinput.Therestof
theapplicationisonhold.Ithastobedismissedbyanexplicituser’saction.
11.Android–UI–TheDialogBox
TheAlertDialog
Warning!!!
AnAlertDialo
g
isNOT at
yp
icalin
p
utBox
(
asin.NET
)
g
yp
p
( )
Why?
AnAlertDialog boxismodalasitneedsuserinterventionto
beterminated
44
However
itdoesnotstopthemainthread(codefollowingthecallto
showtheDialogAlert boxisexecutedwithoutwaitingforthe
user’sinput)
10/4/2011
3
11.Android–UI–TheDialogBox
TheAlertDialog
Dissectingan
AlertDialog Box:
Icon
Title
Negative
Button
Message
55
Positive
Button
Neutral
Button
11.Android–UI–TheDialogBox
TheAlertDialog
Example:AsimpleDialogBox
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout width
="
fill parent
"
android:layout_width
fill_parent
android:layout_height="fill_parent"
xmlns:android="
android:orientation="horizontal">
<Button
android:text="GO"
android:id="@+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<EditText
d idhit
"likth btt "
66
an
d
ro
id
:
hi
n
t
=
"
c
li
c
k
th
e
b
u
tt
on
"
android:id="@+id/txtMsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>
10/4/2011
4
11.Android–UI–TheDialogBox
TheAlertDialog
Example: Asimpledialogbox
package cis493.selectionwidgets;
it
did Atiit
i
mpor
t
an
d
ro
id
.app.
A
c
ti
v
it
y
;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AndDemoUI1 extends Activity {
77
Button btnGo;
EditText txtMsg;
String msg;
11.Android–UI–TheDialogBox
TheAlertDialog
Example: Asimpledialogbox
@Override
public void onCreate(Bundle savedInstanceState) {
super
.onCreate
(
savedInstanceState
);
super
.onCreate
(
savedInstanceState
);
setContentView(R.layout.main);
txtMsg = (EditText)findViewById(R.id.txtMsg);
btnGo = (Button) findViewById(R.id.btnGo);
btnGo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
AlertDialog dialBox = createDialogBox();
dialBox.show();
// WARNING: (in general )
// after showing a dialog you should have NO more code. Let the buttons of
88
// the dialog box handle the rest of the logic. For instance, in this
// example a modal dialog box is displayed (once shown you can not do
// anything to the parent until the child is closed) however the code in
// the parent continues to execute after the show() method is
// called.
txtMsg.setText("I am here! ");
}
});
}//onCreate
10/4/2011
5
11.Android–UI–TheDialogBox
TheAlertDialog
Example: Asimpledialogbox
private AlertDialog createDialogBox(){
AlertDialo
g
m
yQ
uittin
g
Dialo
g
Box
=
g
yQ g g
new AlertDialog.Builder(this)
//set message, title, and icon
.setTitle("Terminator")
.setMessage("Are you sure that you want to quit?")
.setIcon(R.drawable.ic_menu_end_conversation)
//set three option buttons
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//whatever should be done when answering "YES" goes here
"YES "
It
tSti
(
hi hB tt
)
99
msg =
"YES
"
+
I
n
t
eger.
t
o
St
r
i
ng
(
whi
c
hB
u
tt
on
)
;
txtMsg.setText(msg);
}
})//setPositiveButton
11.Android–UI–TheDialogBox
TheAlertDialog
Example: Asimpledialogbox
.setNeutralButton("Cancel",new DialogInterface.OnClickListener() {
p
ublic void onClick
(
D
ialo
g
Interface
d
ialo
g
,
i
nt
w
hichButton
)
{
p
g
g
//whatever should be done when answering "CANCEL" goes here
msg = "CANCEL " + Integer.toString(whichButton);
txtMsg.setText(msg);
}//OnClick
})//setNeutralButton
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//whatever should be done when answering "NO" goes here
msg = "NO " + Integer.toString(whichButton);
txtMsg.setText(msg);
}
})
//
setNegativeButton
1010
})
//
setNegativeButton
.create();
.return myQuittingDialogBox;
}// createDialogBox
}// class
10/4/2011
6
11.Android–UI–TheDialogBox
TheAlertDialog
Example: AsimpleAlertDialog box
Thistextisset
right after
right
after
showingthe
dialogbox
1111
11.Android–UI–TheDialogBox
TheToastView
AToast isatransientview
containingaquicklittlemessage
fortheuser.
Theyappearasafloatingview
overtheapplication.
Toastsneverreceivefocus!
1212
10/4/2011
7
11.Android–UI–TheDialogBox
TheToastView
Example: AsimpleToast
Toast.makeText ( context, message, duration ).show();
Context:Areferencetotheview’senvironment(whatisaroundme…)
Message:Thethingyouwanttosay
Duration:SHORT(0)orLONG(1)exposure
1313
11.Android–UI–TheDialogBox
TheToastView
Example: AsimpleToast
package cis493.dialogboxes;
it
d id A ti it
i
mpor
t
an
d
ro
id
.app.
A
c
ti
v
it
y
;
import android.os.Bundle;
import android.widget.Toast;
public class ToastDemo1 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView
(
R.layout.
main
);
1414
setContentView
(
R.layout.
main
);
Toast.makeText(
getApplicationContext(),
"Saludos amigos \n Hasta la vista",
Toast.LENGTH_LONG).show();
}
}
10/4/2011
8
11.Android–UI–TheDialogBox
TheToastView
Asanaside
Context:
OnAndroidaContextismostlyusedtoloadandaccessresources.
AllwidgetsreceiveaContextparameterintheirconstructor.
InaregularAndroidapplication,youusuallyhavetwokindsofContext,
Activity andApplication.Thefirstoneistypicallypassedtoclasses
andmethodsthatneedaContext.
1515
Viewshaveareferencetotheentireactivityandthereforetoanythingyour
activityisholdingonto;usuallytheentireViewhierarchyandallitsresources.
11.Android–UI–TheDialogBox
TheToastView
CustomizingaToastView
B
y
defaultToastviewsaredis
p
la
y
edatthecenter‐bott omofthe
y py
screen.
HowevertheusermaychangetheplacementofaToastviewby
usingeitherofthefollowingmethods:
void setGravity (int gravity, int xOffset, int yOffset)
Set the location at which the notification should appear on the screen.
1616
Set
the
location
at
which
the
notification
should
appear
on
the
screen.
void setMargin (float horizontalMargin, float verticalMargin)
Setthemarginsoftheview.
10/4/2011
9
11.Android–UI–TheDialogBox
TheToastView
CustomizingaToastView
Thefollowin
g
methodusesoffsetvaluesbasedonthe
p
ixel
g p
resolutionoftheactualdevice.Forinstance,theG1phonescreen
contains360x480pixels.
void setGravity (int gravity, int xOffset, int yOffset)
Gravity: Overallplacement.Typicalvaluesinclude:Gravity.CENTER,Gravity.TOP,
Gravity.BOTTOM,…
1717
xOffset: AssumeGravity.CENTER placementonaG1phone.The
xOffset rangeis‐160,…,0,…160(left,center,right)
yOffset:TherangeonaG1is:‐240,…,0,…240(top,center, bottom)
11.Android–UI–TheDialogBox
TheToastView
CustomizingtheToastView
AsecondmethodtoplaceaToastissetMargin.Thescreenisconsideredtohave
acenterpointwherehorizontalandverticalcenterlinesmeet.Thereis50%of
thescreentoeachsideofthatcenterpoint(top,botton,left,right).Marginsare
expressedasavaluebetween:‐50,…,0,…,50.
void setMargin (float horizontalMargin, float verticalMargin)
1818
Note:
Thepairofmargins(‐50,‐50)representtheupper‐leftcornerofthescreen,
(0,0)isthecenter,and(50,50)thelower‐rightcorner.
10/4/2011
10
11.Android–UI–TheDialogBox
TheToastView
Example: ChangingtheplacementofaToastview.
1919
UsingthesetGravity(…) methodwithGravity.CENTER,andxandyoffsetsof(resp.):
0,0(center)
‐160,‐240 (top‐left)
160,240 (right‐bottom)
11.Android–UI–TheDialogBox
TheToastView
Example: ChangingtheplacementofaToastview.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
android:id="@+id/myTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
android:stretchColumns="1,2"
xmlns:android=" />>
android:inputType="numberSigned"
>
</EditText>
</TableRow>
<TableRow
android:id="@+id/myRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0000ff"
android:padding
=
"10px
"
>
<TableRow
android:id="@+id/myRow1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/myCaption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff009999"
android:text="Testing Toast - Gravity.CENTER 320x480 pixels"
android:textSize="20sp"
android:gravity="center"
android:layout_span="2"
>
</TextView>
</TableRow>
<TableRow
android:id="@+id/myRow1"
android:layout
_
width
=
"fill
_
parent"
android:padding
=
10px
android:orientation="horizontal"
>
<TextView
android:id="@+id/yLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Y offset: "
android:textSize="18sp"
>
</TextView>
<EditText
android:id="@+id/yBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="18sp"
android:inputType="numberSigned"
>
</EditText>
</TableRow>
<
T
ableRow
2020
_
_
android:layout_height="wrap_content"
android:background="#ff0000ff"
android:padding="10px"
android:orientation="horizontal"
>
<TextView
android:id="@+id/xLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" X offset: "
android:textSize="18sp"
>
</TextView>
<EditText
android:id="@+id/xBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="18sp"
android:id="@+id/myRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0000ff"
android:padding="10px"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Show Toast "
android:layout_span="2"
>
</Button>
</TableRow>
</TableLayout>
10/4/2011
11
11.Android–UI–TheDialogBox
TheToastView
Example: ChangingtheplacementofaToastview.
package cis493.dialogboxes;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ToastDemo1 extends Activity {
EditText xBox;
EditText
yBox
;
2121
EditText
yBox
;
Button btn1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
xBox = (EditText)findViewById(R.id.xBox);
yBox = (EditText)findViewById(R.id.yBox);
11.Android–UI–TheDialogBox
TheToastView
Example: ChangingtheplacementofaToastview.
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
Toast myToast = Toast.makeText(
getApplicationContext(),
"Saludos amigos \n Hasta la vista",
Toast.LENGTH_LONG);
myToast.setGravity(Gravity.CENTER,
Integer.valueOf(xBox.getText().toString()),
Integer.valueOf(yBox.getText().toString()) );
myToast.show();
2222
} catch (NumberFormatException e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
}
}// onClick
}); // listener
}// onCreate
}// class
10/4/2011
12
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Toastscouldbemodifiedtodis
p
la
y
acustomcombinationof
py
color/shape/text/background.
Youneedtofollowthenextsteps:
1. DefinetheXMLlayoutofthenewcustomview
2. MakesurethereisaTex tView named:text
3
Additionally you could attach an
android: background
to the
TextView
2323
3
.
Additionally
you
could
attach
an
android:
background
to
the
TextView
.
4. Thebackgroundcouldbeafigure(suchasa.png file)oranXMLdefined
shape(seenextexample).
Exampletakenfrom:
/>11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Let’sbeginwiththeapplication’smain layout.
<?xml version="1.0" encoding
=
"
ut
f
-
8
"
?
>
<LinearLayout
xmlns:android=" />android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#777"
>
<TextView
android:layout_width="fill_parent"
android:la
y
out hei
g
h
t
=
"
wra
p
content"
2424
y_g
p_
android:text='"Testing Custom TOAST"'/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnShowToast"
android:text=" Show Custom - Normal Toast ">
</Button>
</LinearLayout>
10/4/2011
13
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Nowwecreateourcustom Toastlayout(called:
m
y
toast la
y
out.xm
l
.ItmustcontainaTextView called‘tex
t
’
)
y
__
y
)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" />android:id="@+id/my_toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<TextView
android:id
=
"@+id/text"
RequiredTex tV iew
2525
android:id
=
"@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:background="@drawable/my_border"
>
</TextView>
</LinearLayout>
Optionalbackground
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Finallywetakecareoftheoptionalbackgroundelement
(
m
y
border.xm
l
)
.Inthisex am
p
lewedefinea<sha
p
e>
(
butitcould
(
y
_
) p p (
beany.png image).ThisXML(orimage)issavedinthefolder:
/res/drawable
<?xml version="1.0" encoding="UTF-8" ?>
<shape
xmlns:android=" />android:shape="rectangle">
<
stroke
android:width
=
"2dp
"
android:color
=
"#ffffff00
"
/>
2626
<
stroke
android:width
2dp
android:color
#ffffff00
/>
<solid android:color="#ff990000" />
<padding android:left="10dp" android:top="4dp"
android:right="10dp" android:bottom="4dp" />
<corners android:radius="15dp" />
</shape>
10/4/2011
14
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Testingtheapplication
2727
AToastdisplayedwith
ourcustomlayout
AToastdisplayedusing
standardformatting
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
package cis493.dialogboxes;
import android.app.Activity
;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
2828
public class ToastDemo2 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
10/4/2011
15
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Button btnShowToast = (Button) findViewById(R.id.btnShowToast);
btnShowToast.setOnClickListener(new OnClickListener() {
@Override
p blic
oid
onClick
(Vie ) {
p
u
blic
v
oid
onClick
(Vie
w v
)
{
//custom made TOAST
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(
R.layout.my_toast_layout,
(ViewGroup) findViewById(R.id.my_toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
Toast toast = new Toast(getApplicationContext());
text.setText("Hola mundo \nI'm a fancy Toast");
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
2929
toast.setView(layout);
toast.show();
// normal TOAST
Toast.makeText(getApplicationContext(),
"Hola mundo \nnow I am quite normal",
Toast.LENGTH_SHORT).show();
}
});
}
}
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Asanaside:
InflatingaView
YoumaywantoccasionallytomodifythewayAndroidrendersaparticularview
(perhapsadifferentcolor,style,orshape).
OncetheHierarchyViewhasbeendisplayed,youcantakeanyterminalnodeand
extendit byinflatingacustom‘viewsub‐tree’.Also,byusinglayoutinflationwe
maydrawanewHierarchyontopoftheexistingscreen.
Inourexample,ourcustomizedrenditionofaToast box(includingacolorful
bk d)i dfi di XML fil Diti th i f th t Tti
3030
b
ac
k
groun
d)
i
s
d
e
fi
ne
d
i
nan
XML
fil
e.
D
ep
i
c
ti
ng
th
e
i
mageo
f
th
ecus
t
om
T
oas
t
i
s
accomplishedbyinflatingtheXMLlayoutspec.
10/4/2011
16
11.Android–UI–TheDialogBox
TheToastView
Example:ShowingFancyToastviews.
Asanaside:
InflatingaView
Syntaxt
public View inflate (int resource, ViewGroup root)
Inflateanewviewhierarchyfromthespecifiedxmlresource.
Parameters
resourceIDforanXMLlayoutresourcetoload,root:optionalviewtobetheparentofthe
generatedhierarchy.
Returns
TherootViewoftheinflatedhierarchy.Ifrootwassupplied,thisistherootView;otherwise
itisthe
rootoftheinflatedXMLfile.
3131
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(
R.layout.my_toast_layout,
(ViewGroup) findViewById(R.id.my_toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
11.Android–UI–TheDialogBox
DialogBoxes
323232
10/4/2011
17
11.Android–UI–TheDialogBox
DialogBoxes
AppendixA.Density‐independentpixel(dp ordip)
AvirtualpixelunitthatyoushouldusewhendefiningUIlayout,toexpresslayout
dimensionsorpositioninadensity‐independentway.
Thedensity‐independentpixelisequivalenttoonephysicalpixelona160dpiscreen,
whichisthebaselinedensityassumedbythesystemfora"medium"densityscreen.
Atruntime,thesystemtransparentlyhandlesanyscalingofthedp units,asnecessary,
basedontheactualdensityofthescreeninuse.Theconversionofdp unitstoscreen
ili il
d
* (d i / 160)
333333
p
i
xe
l
s
i
ss
i
mp
l
e: px =
d
p
*
(d
p
i
/
160)
.
Forexample,ona240dpiscreen,1dp equals1.5physicalpixels.Youshouldalwaysuse
dp unitswhendefiningyourapplication'sUI,toensureproperdisplayofyourUIon
screenswithdifferentdensities.