Android Chapter11 DialogBoxes
Transcript of Android Chapter11 DialogBoxes
-
10/4/2011
1
A d id
11
AndroidDialogBoxes
AlertDialog &ToastWidgetsVictorMatos
ClevelandStateUniversityNotesarebasedon:
AndroidDevelopershttp://developer.android.com/index.html
11.Android UI TheDialogBox
TheDialogBoxAndroidprovidestwoprimitiveformsofdialogboxes:1. AlertDialog boxes,and2. Toastcontrols
22
-
10/4/2011
2
11.Android UI TheDialogBox
TheAlertDialogTheAlertDialog isanalmost modal screenthat
(1) presentsabriefmessagetotheusertypicallyshownasasmallfloatingwindowthatpartiallyobscurestheunderlyingview,and
(2) collectsasimpleanswer(usuallyby
333
clickinganoptionbutton).
Note:Afullymodal viewremainsonthescreenwaitingforusersinput.Therestoftheapplicationisonhold.Ithastobedismissedbyanexplicitusersaction.
11.Android UI TheDialogBox
TheAlertDialogWarning!!!AnAlertDialog isNOT atypicalinputBox (asin.NET)g yp p ( )Why?
AnAlertDialog boxismodalasitneedsuserinterventiontobeterminated
44
Howeveritdoesnotstopthemainthread(codefollowingthecalltoshowtheDialogAlert boxisexecutedwithoutwaitingfortheusersinput)
-
10/4/2011
3
11.Android UI TheDialogBox
TheAlertDialogDissectinganAlertDialog Box: Icon
Title
NegativeButtonMessage
55
PositiveButton
NeutralButton
11.Android UI TheDialogBox
TheAlertDialogExample:AsimpleDialogBox
-
10/4/2011
4
11.Android UI TheDialogBox
TheAlertDialogExample: Asimpledialogboxpackage cis493.selectionwidgets;i t d id A ti itimport android.app.Activity;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
TheAlertDialogExample: Asimpledialogbox
@Overridepublic 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() {
@Overridepublic 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
TheAlertDialogExample: Asimpledialogboxprivate AlertDialog createDialogBox(){
AlertDialog myQuittingDialogBox = 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 " I t t St i ( hi hB tt )
99
msg = "YES " + Integer.toString(whichButton);txtMsg.setText(msg);
} })//setPositiveButton
11.Android UI TheDialogBox
TheAlertDialogExample: Asimpledialogbox
.setNeutralButton("Cancel",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int whichButton) {p g g
//whatever should be done when answering "CANCEL" goes heremsg = "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 heremsg = "NO " + Integer.toString(whichButton);txtMsg.setText(msg);
} })//setNegativeButton
1010
})//setNegativeButton
.create();
.return myQuittingDialogBox;}// createDialogBox
}// class
-
10/4/2011
6
11.Android UI TheDialogBox
TheAlertDialogExample: AsimpleAlertDialog box
Thistextissetright afterrightaftershowingthedialogbox
1111
11.Android UI TheDialogBox
TheToastViewAToast isatransientviewcontainingaquicklittlemessagefortheuser.Theyappearasafloatingviewovertheapplication.Toastsneverreceivefocus!
1212
-
10/4/2011
7
11.Android UI TheDialogBox
TheToastViewExample: AsimpleToastToast.makeText ( context, message, duration ).show();
Context: Areferencetotheviewsenvironment(whatisaroundme)Message: ThethingyouwanttosayDuration: SHORT(0)orLONG(1)exposure
1313
11.Android UI TheDialogBox
TheToastViewExample: AsimpleToastpackage cis493.dialogboxes;i t d id A ti itimport android.app.Activity;import android.os.Bundle;import android.widget.Toast;public class ToastDemo1 extends Activity {
/** Called when the activity is first created. */@Overridepublic 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
TheToastViewAsanasideContext:
OnAndroidaContextismostlyusedtoloadandaccessresources.AllwidgetsreceiveaContextparameterintheirconstructor.InaregularAndroidapplication,youusuallyhavetwokindsofContext,Activity andApplication.ThefirstoneistypicallypassedtoclassesandmethodsthatneedaContext.
1515
Viewshaveareferencetotheentireactivityandthereforetoanythingyouractivityisholdingonto;usuallytheentireViewhierarchyandallitsresources.
11.Android UI TheDialogBox
TheToastViewCustomizingaToastViewBydefaultToastviewsaredisplayedatthecenterbottomofthey p yscreen.HowevertheusermaychangetheplacementofaToastviewbyusingeitherofthefollowingmethods:void setGravity (int gravity, int xOffset, int yOffset) Set the location at which the notification should appear on the screen.
1616
Setthelocationatwhichthenotificationshouldappearonthescreen.void setMargin (float horizontalMargin, float verticalMargin) Setthemarginsoftheview.
-
10/4/2011
9
11.Android UI TheDialogBox
TheToastViewCustomizingaToastViewThefollowingmethodusesoffsetvaluesbasedonthepixelg presolutionoftheactualdevice.Forinstance,theG1phonescreencontains360x480pixels.void setGravity (int gravity, int xOffset, int yOffset)
Gravity:Overallplacement.Typicalvaluesinclude:Gravity.CENTER,Gravity.TOP,Gravity.BOTTOM,
1717
xOffset: AssumeGravity.CENTER placementonaG1phone.ThexOffset rangeis160,,0,160(left,center,right)
yOffset: TherangeonaG1is:240,,0,240(top,center,bottom)
11.Android UI TheDialogBox
TheToastViewCustomizingtheToastViewAsecondmethodtoplaceaToastissetMargin.Thescreenisconsideredtohaveacenterpointwherehorizontalandverticalcenterlinesmeet.Thereis50%ofthescreentoeachsideofthatcenterpoint(top,botton,left,right).Marginsareexpressedasavaluebetween:50,,0,,50.
void setMargin (float horizontalMargin, float verticalMargin)
1818
Note:Thepairofmargins(50,50)representtheupperleftcornerofthescreen,(0,0)isthecenter,and(50,50)thelowerrightcorner.
-
10/4/2011
10
11.Android UI TheDialogBox
TheToastViewExample: ChangingtheplacementofaToastview.
1919
UsingthesetGravity()methodwithGravity.CENTER,andxandyoffsetsof(resp.):0,0 (center)160,240 (topleft)160,240 (rightbottom)
11.Android UI TheDialogBox
TheToastViewExample: ChangingtheplacementofaToastview.
android:inputType="numberSigned">
-
10/4/2011
11
11.Android UI TheDialogBox
TheToastViewExample: 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;
@Overridepublic 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
TheToastViewExample: ChangingtheplacementofaToastview.btn1 = (Button)findViewById(R.id.btn1);btn1.setOnClickListener(new OnClickListener() {
@Overridepublic 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
TheToastViewExample:ShowingFancyToastviews.Toastscouldbemodifiedtodisplayacustomcombinationofp ycolor/shape/text/background.Youneedtofollowthenextsteps:1. DefinetheXMLlayoutofthenewcustomview2. MakesurethereisaTextView named:text3 Additionally you could attach an android: background to the TextView
2323
3. Additionallyyoucouldattachanandroid:background totheTextView.4. Thebackgroundcouldbeafigure(suchasa.png file)oranXMLdefined
shape(seenextexample).
Exampletakenfrom:http://hustleplay.wordpress.com/2009/07/23/replicatingdefaultandroidtoast/
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.Letsbeginwiththeapplicationsmain layout.
-
10/4/2011
13
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.Nowwecreateourcustom Toastlayout(called:my toast layout.xml.ItmustcontainaTextView calledtext)y_ _ y )
Optionalbackground
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.Finallywetakecareoftheoptionalbackgroundelement(my border.xml).Inthisexamplewedefinea(butitcould( y_ ) p p (beany.png image).ThisXML(orimage)issavedinthefolder:/res/drawable
2626
-
10/4/2011
14
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.Testingtheapplication
2727
AToastdisplayedwithourcustomlayout
AToastdisplayedusingstandardformatting
11.Android UI TheDialogBox
TheToastViewExample: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 {@Overridepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.main);
-
10/4/2011
15
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.Button btnShowToast = (Button) findViewById(R.id.btnShowToast);btnShowToast.setOnClickListener(new OnClickListener() {
@Overridep blic oid onClick(Vie ) {public void onClick(View v) {
//custom made TOASTLayoutInflater 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 TOASTToast.makeText(getApplicationContext(),
"Hola mundo \nnow I am quite normal", Toast.LENGTH_SHORT).show();
} });
}}
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.
Asanaside:InflatingaViewYoumaywantoccasionallytomodifythewayAndroidrendersaparticularview(perhapsadifferentcolor,style,orshape).OncetheHierarchyViewhasbeendisplayed,youcantakeanyterminalnodeandextendit byinflatingacustomviewsubtree.Also,byusinglayoutinflationwemaydrawanewHierarchyontopoftheexistingscreen.Inourexample,ourcustomizedrenditionofaToastbox(includingacolorfulb k d) i d fi d i XML fil D i ti th i f th t T t i
3030
background)isdefinedinanXMLfile.DepictingtheimageofthecustomToastisaccomplishedbyinflatingtheXMLlayoutspec.
-
10/4/2011
16
11.Android UI TheDialogBox
TheToastViewExample:ShowingFancyToastviews.
Asanaside:InflatingaViewSyntaxtpublic View inflate (int resource, ViewGroup root)
Inflateanewviewhierarchyfromthespecifiedxmlresource.Parameters
resourceIDforanXMLlayoutresourcetoload,root:optionalviewtobetheparentofthegeneratedhierarchy.
ReturnsTherootViewoftheinflatedhierarchy.Ifrootwassupplied,thisistherootView;otherwiseitistherootoftheinflatedXMLfile.
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
DialogBoxesAppendixA.Densityindependentpixel(dp ordip)AvirtualpixelunitthatyoushouldusewhendefiningUIlayout,toexpresslayoutdimensionsorpositioninadensityindependentway.Thedensityindependentpixelisequivalenttoonephysicalpixelona160dpiscreen,whichisthebaselinedensityassumedbythesystemfora"medium"densityscreen.Atruntime,thesystemtransparentlyhandlesanyscalingofthedp units,asnecessary,basedontheactualdensityofthescreeninuse.Theconversionofdp unitstoscreeni l i i l d * (d i / 160)
333333
pixelsissimple: px =dp *(dpi/160).Forexample,ona240dpiscreen,1dp equals1.5physicalpixels.Youshouldalwaysusedp unitswhendefiningyourapplication'sUI,toensureproperdisplayofyourUIonscreenswithdifferentdensities.