android chapter11 dialog boxes

Upload: x-man

Post on 06-Apr-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Android Chapter11 Dialog Boxes

    1/16

    9/16/2009

    1

    11

    n ro

    DialogBoxesAlertDialog Toast

    VictorMatos

    ClevelandStateUniversity

    Notesarebasedon:

    AndroidDevelopers

    http://developer.android.com/index.html

    11.Android UI TheDialogBox

    TheDialogBox

    Androidprovidestwoprimitiveformsof

    dialogboxes:

    1. AlertDialog boxes,and

    2. Toasts

    AnAlertDialog showsafloatingscreen

    andwaitsfortheusertoclickona

    buttontobedismissed.

    22

    AToast brieflydisplaysamessage

    (about23sec.)andquietly

    disappears.

  • 8/3/2019 Android Chapter11 Dialog Boxes

    2/16

    9/16/2009

    2

    11.Android UI TheDialogBox

    TheAlertDialog

    TheAlertDialog isanalmostmodalscreen

    that

    (1) presentsabriefmessagetotheuser

    typicallyshownasasmallfloating

    windowthatpartiallyobscuresthe

    underlyingview,and

    (2) collectsasimpleanswer(usuallyby

    333

    clickinganoptionbutton).

    Note:

    Amodal viewremainsonthescreenwaitingforusersinput.

    Itishastobedismissedbyanexplicitusersaction.

    11.Android UI TheDialogBox

    TheAlertDialog

    Warning!!!AnAlertDialo isNOTat icalin utBox asin.NET

    Why?

    AnAlertDialog boxismodalasitneedsuserinterventionto

    beterminated

    HOWEVER

    44

    itdoesnotstopthemainthread(codefollowingthecallto

    showtheDialogAlertboxisexecutedwithoutwaitingforthe

    usersinput)

  • 8/3/2019 Android Chapter11 Dialog Boxes

    3/16

    9/16/2009

    3

    11.Android UI TheDialogBox

    TheAlertDialog

    Example:

    Icon

    Title

    Negative

    ButtonMessage

    55

    Positive

    Button

    Neutral

    Button

    11.Android UI TheDialogBox

    TheAlertDialog

    Example:AsimpleDialogBox

  • 8/3/2019 Android Chapter11 Dialog Boxes

    4/16

    9/16/2009

    4

    11.Android UI TheDialogBox

    TheAlertDialog

    Example: Asimpledialogbox

    package cis493.selectionwidgets;

    import 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

    TheAlertDialog

    Example: Asimpledialogbox

    @Override

    public void onCreate(Bundle savedInstanceState) {

    su er.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 diaBox = createDialogBox();

    diaBox.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

  • 8/3/2019 Android Chapter11 Dialog Boxes

    5/16

    9/16/2009

    5

    11.Android UI TheDialogBox

    TheAlertDialog

    Example: Asimpledialogbox

    private AlertDialog createDialogBox(){

    AlertDialog myQuittingDialogBox =

    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

    99

    msg = "YES " + Integer.toString(whichButton);

    txtMsg.setText(msg);

    }

    })//setPositiveButton

    11.Android UI TheDialogBox

    TheAlertDialog

    Example: Asimpledialogbox

    .setNeutralButton("Cancel",new DialogInterface.OnClickListener() {

    ublic void onClick(DialogInterface dialog, int whichButton) {

    //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);

    }

    1010

    set egative utton

    .create();

    .return myQuittingDialogBox;

    }// createDialogBox

    }// class

  • 8/3/2019 Android Chapter11 Dialog Boxes

    6/16

    9/16/2009

    6

    11.Android UI TheDialogBox

    TheAlertDialog

    Example: AsimpleAlertDialog box

    Thistextisset

    showingthe

    dialogbox

    1111

    11.Android UI TheDialogBox

    TheToastView

    AToast isatransientview

    containingaquicklittlemessage

    fortheuser.

    Theyappearasafloatingview

    overtheapplication.

    Theyneverreceivefocus.

    1212

  • 8/3/2019 Android Chapter11 Dialog Boxes

    7/16

    9/16/2009

    7

    11.Android UI TheDialogBox

    TheToastView

    Example: AsimpleToast

    Toast.makeText ( context, message, duration ).show();

    Context: Areferencetotheviewsenvironment(whatisaroundme)

    Message: Thethingyouwanttosay

    Duration: SHORTorLONGexposure

    1313

    11.Android UI TheDialogBox

    TheToastView

    Example: AsimpleToast

    package cis493.dialogboxes;

    mport an ro .app.Act v ty;

    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.la out.main

    1414

    . .

    Toast.makeText(

    getApplicationContext(),

    "Saludos amigos \n Hasta la vista",

    Toast.LENGTH_LONG).show();

    }

    }

  • 8/3/2019 Android Chapter11 Dialog Boxes

    8/16

    9/16/2009

    8

    11.Android UI TheDialogBox

    TheToastView

    AsanasideContext:

    OnAndroidaContextismostlyusedtoloadandaccessresources.

    AllwidgetsreceiveaContextparameterintheirconstructor.

    InaregularAndroidapplication,youusuallyhavetwokindsofContext,

    ActivityandApplication.Thefirstoneistypicallypassedtoclasses

    andmethodsthatneedaContext.

    1515

    Viewshaveareferencetotheentireactivityandthereforetoanythingyour

    activityisholding onto;usuallytheentireViewhierarchyandallitsresources.

    11.Android UI TheDialogBox

    TheToastView

    CustomizingaToastViewB defaultToastviewsaredis la edatthecenterbottomofthe

    screen.

    HowevertheusermaychangetheplacementofaToastviewby

    usingeitherofthefollowingmethods:

    void setGravity (int gravity, int xOffset, int yOffset)

    Set the location at which the notification should a ear on the screen.

    1616

    .

    void setMargin (float horizontalMargin, float verticalMargin)

    Setthemarginsoftheview.

  • 8/3/2019 Android Chapter11 Dialog Boxes

    9/16

    9/16/2009

    9

    11.Android UI TheDialogBox

    TheToastView

    CustomizingaToastViewThefollowin methodusesoffsetvaluesbasedonthe ixel

    resolutionoftheactualdevice.Forinstance,theG1phonescreen

    contains360x480pixels.

    void setGravity (int gravity, int xOffset, int yOffset)

    Gravity:Overallplacement.Typicalvaluesinclude:Gravity.CENTER,Gravity.TOP,

    Gravity.BOTTOM,

    1717

    xOffset: Assume

    Gravity.CENTER placement

    on

    a

    G1

    phone.

    The

    xOffsetrangeis 160,,0,160(left,center,right)

    yOffset: TherangeonaG1is: 240,,0,240(top,center,bottom)

    11.Android UI TheDialogBox

    TheToastView

    CustomizingtheToastViewAsecondmethodtoplaceaToastissetMargin.Thescreenisconsideredtohave

    acenterpointwherehorizontalandverticalcenterlinesmeet.Thereis50% of

    thescreentoeachsideofthatcenterpoint(top,botton,left,right).Marginsare

    expressedasavaluebetween: 50,,0,,50.

    void setMargin (float horizontalMargin, float verticalMargin)

    1818

    Note:

    Thepair

    of

    margins

    (50,

    50)

    represent

    the

    upper

    left

    corner

    of

    the

    screen,

    (0,0)isthecenter,and(50,50)thelowerrightcorner.

  • 8/3/2019 Android Chapter11 Dialog Boxes

    10/16

    9/16/2009

    10

    11.Android UI TheDialogBox

    TheToastView

    Example: ChangingtheplacementofaToastview.

    1919

    UsingthesetGravity() methodwith Gravity.CENTER,andxandyoffsetsof(resp.):

    0,0 (center)

    160, 240 (topleft)

    160,240 (rightbottom)

    11.Android UI TheDialogBox

    TheToastViewExample: Changing

    the

    placement

    of

    aToast

    view.

    android:inputType="numberSigned"

    >

  • 8/3/2019 Android Chapter11 Dialog Boxes

    11/16

    9/16/2009

    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 Box

    2121

    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

  • 8/3/2019 Android Chapter11 Dialog Boxes

    12/16

    9/16/2009

    12

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Toastscouldbemodifiedtodis la acustomcombinationof

    color/shape/text/background.

    Youneedtofollowthenextsteps:

    1. DefinetheXMLlayoutofthenewcustomview

    2. MakesurethereisaTextViewnamed: text

    2323

    . .

    4. Thebackgroundcouldbeafigure(suchasa.png file)oranXMLdefined

    shape(see

    next

    example).

    Exampletakenfrom:

    http://hustleplay.wordpress.com/2009/07/23/replicating defaultandroidtoast/

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Letsbeginwiththeapplicationsmain layout.

  • 8/3/2019 Android Chapter11 Dialog Boxes

    13/16

    9/16/2009

    13

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Nowwecreateourcustom Toastlayout(called:

    m toast la out.xml. ItmustcontainaTextView calledtext_ _

    Optionalbackground

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Finallywetakecareoftheoptionalbackgroundelement

    m border.xml .Inthisexam lewedefinea butitcould_

    beany.png image).ThisXML(orimage)issavedinthefolder:

    /res/drawable

    r n r i i h=" " =" ffffff " >

    2626

  • 8/3/2019 Android Chapter11 Dialog Boxes

    14/16

  • 8/3/2019 Android Chapter11 Dialog Boxes

    15/16

    9/16/2009

    15

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Button btnShowToast = (Button) findViewById(R.id.btnShowToast);

    btnShowToast.setOnClickListener(new OnClickListener() {

    @Override

    pu c vo on c ew 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 TOASTToast.makeText(getApplicationContext(),

    "Hola mundo \nnow I am quite normal",

    Toast.LENGTH_SHORT).show();

    }

    });

    }

    }

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Asanaside:

    InflatingaViewYoumaywantoccasionallytomodifythewayAndroidrendersaparticularview

    (perhapsadifferentcolor,style,orshape).

    OncetheHierarchyViewhasbeendisplayed,youcantakeanyterminalnodeand

    extendit byinflatingacustomviewsubtree. Also,byusinglayoutinflationwemaydrawanewHierarchyontopoftheexistingscreen.

    Inourexample,ourcustomizedrenditionofaToastbox(includingacolorful

    3030

    ac groun s e ne nan e. ep c ng e mageo ecus om oas s

    accomplishedby

    inflating

    the

    XML

    layout

    spec.

  • 8/3/2019 Android Chapter11 Dialog Boxes

    16/16

    9/16/2009

    16

    11.Android UI TheDialogBox

    TheToastView

    Example:ShowingFancyToastviews.Asanaside:

    InflatingaViewSyntaxt

    public View inflate (int resource, ViewGroup root)

    Inflateanewviewhierarchyfromthespecifiedxmlresource.

    Parameters

    resourceIDforanXMLlayoutresourcetoload, root:optionalviewtobetheparentofthe

    generatedhierarchy.

    Returns

    TherootViewoftheinflatedhierarchy.Ifrootwassupplied,thisistherootView;otherwise

    itistherootoftheinflatedXMLfile.

    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

    Questions?

    323232