SlideShare une entreprise Scribd logo
1  sur  8
Android Application Development Training Tutorial




                      For more info visit

                   http://www.zybotech.in




        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Android Basics – Dialogs and Floating Activities
As we know android provide Activity class for developing application screens. But many a time application
needs to show Dialog boxes or floating screen to do simple tasks likes taking input from user or ask for
confirmation etc.

In android Dialogs can be created in following 2 ways:

1. Creating a dialog with the help of android Dialog class or its subclass like AlertDialog.
2. Using dialog theme for the activity.

Using android Dialog class:
Let see how we can create a dialog with the help of Dialog class. To define a dialog the dialog class has to
extend the android Dialog class.

class MyDialog extends Dialog {
/**
* @param context
*/
public MyDialog(Context context) {
super(context);
}
}

Define a layout for our dialog. Here is the xml file for of the layout that asks for user’s name.

<?xml version=”1.0″ encoding=”utf-8″?>


<LinearLayout
android:id="@+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/nameMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter Name:"
>
</TextView>
<EditText
android:id="@+id/nameEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
>
</EditText>
<LinearLayout


                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
android:id="@+id/buttonLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
<Button
android:id="@+id/okButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
>
</Button>
<Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
>
</Button>
</LinearLayout>
</LinearLayout>

Use the above layout for our dialog

class MyDialog extends Dialog {
....

/**

* @see android.app.Dialog#onCreate(android.os.Bundle)

*/

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Log.d("TestApp", "Dialog created");

setContentView(R.layout.mydialog);

}

}

Now the dialog can be shown by calling the show method like this

…

MyDialog dialog = new MyDialog(context);
dialog.show();

…


                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Event handling for the Dialog controls are same as in case of the activity. Modify the dialog code to handle the
onclick event on the ok and cancel button.

class MyDialog extends Dialog implements OnClickListener {

private Button                 okButton;

private Button                 cancelButton;

private EditText               nameEditText;

protected void onCreate(Bundle savedInstanceState) {

okButton = (Button) findViewById(R.id.okButton);

cancelButton = (Button) findViewById(R.id.cancelButton);

nameEditText = (EditText) findViewById(R.id.nameEditText);

okButton.setOnClickListener(this);

cancelButton.setOnClickListener(this);

}




public void onClick(View view) {

switch (view.getId()) {

case R.id.okButton:

dismiss();

break;

case R.id.cancelButton:

cancel();

break;

}

}

}

To close the dialog the dismiss() method can be called. The dialog can call the dismiss method itself or some
other code can also close the dialog by calling dismiss().




                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
The dialog also supports cancel. Canceling means the dialog action is canceled and does not need to perform
any operation. Dialog can be canceled by calling cancel() method. Canceling the dialog also dismisses the
dialog.

When user clicks the phones BACK button the dialog gets canceled. If you do not want to cancel the dialog on
BACK button you can set cancelable to false as

setCancelable(false);

Note that the cancel() method call till be able to cancel the dialog (which is the desirable functionality in most
cases). The dialog’s cancel and dismiss events can be listened with the help of OnCancelListener and
OnDismissListener.

Returning information from dialog:
Now our dialog can take the name from the user. We need to pass that name to the calling activity. Dialog class
does not provide any direct method for returning values. But our own Listener can be created as follows:

public interface MyDialogListener {

public void onOkClick(String name); // User name is provided here.

public void onCancelClick();

}

The dialog’s constructor has to be modified to take the object of the listener:

public MyDialog(Context context, MyDialogListener listener) {
super(context);
this.listener = listener;
}

Now the calling activity needs to provide the object of the class that implements the MyDialogListener which
will gets called on ok or cancel button clicks.

Now we need update the onclick method to return the user name.

public void onClick(View view) {
switch (view.getId()) {
case R.id.okButton:
listener.onOkClick(nameEditText.getText().toString()); // returning the user's name.
dismiss();
break;
case R.id.cancelButton:
cancel();
break;
}
}

Using AlertDialog:

AlertDialog is the subclass of the Dialog. It by default provide 3 buttons and text message. The buttons can be
made visible as required. Following code creates an AlertDialog that ask user a question and provide Yes, No
option.
                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
AlertDialog dialog = new AlertDialog.Builder(context).create();

dialog.setMessage("Do you play cricket?");

dialog.setButton("Yes", myOnClickListener);

dialog.setButton2("No", myOnClickListener);

dialog.show();

The onClick method code for the button listener myOnClickListener will be like this:

public void onClick(DialogInterface dialog, int i) {
switch (i) {
case AlertDialog.BUTTON1:
/* Button1 is clicked. Do something */
break;
case AlertDialog.BUTTON2:
/* Button2 is clicked. Do something */
break;
}
}

AlertDialog.Builder:
AlertDialog has a nested class called ‘Builder’. Builder class provides facility to add multichoice or single
choice lists. The class also provides methods to set the appropriate Adaptors for the lists, set event handlers for
the list events etc. The Builder button calls the Button1, Button2, Button3 as PositiveButton, NeutralButton,
NegativeButton.

Here is an example of dialog box with Multichoice list

new AlertDialog.Builder(context)
.setIcon(R.drawable.icon)
.setTitle(R.string.alert_dialog_multi_choice)
.setMultiChoiceItems(R.array.select_dialog_items,
new boolean[]{false, true, false, true, false},
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
/* Something on click of the check box */
}
})
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked Yes so do some stuff */

}

})

.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked No so do some stuff */



                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
}

})

.create();

Activity Managed Dialog:

Android also provide facility to create dialogs. Activity created dialog can be managed by Activity methods
like showDialog(), onCreateDialog(), onPrepareDialog(), dismissDialog(), removeDialog().
The onCreateDialog create the dialog that needs to be shown, for example

/**
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
return new AlertDialog.Builder(this).setMessage("How are you?").setPositiveButton("Fine",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

/* Do something here */

}

}).setNegativeButton("Not so good", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

/* Do something here */

}

}).create();

}

You can create multiple dialog boxes and differentiate them with the id parameter. The dialog can be shown
with the help of showDialog(id) method. The onCreateDialog method gets called for the first time when
showDialog method is called. For subsequent calls to the showDialog() the dialog is not created but shown
directly.
If you need to update the dialog before it is getting shown then you can do that in onPrepareDialog() method.
The methods get called just before the dialog is shown to the user.
To close the dialog you can call dismissDialog() method. Generally you will dismiss the dialogs in the click
handles of the dialog buttons.
The removeDialog() method will remove the dialog from the activity management and if showDialog is again
called for that dialog, the dialog needs to be created.

Using android Dialog theme for activity:
Another simple way to show the dialog is to make the Activity to work as a Dialog (floating activity). This can
be done by applying dialog Theme while defining the activity entry in the AndroidManifest.xml


                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
<activity android:name=”.DialogActivity” android:label=”@string/activity_dialog”
android:theme=”@android:style/Theme.Dialog”>
…
</activity>

The activity will be shown as a dialog as the activity is using ‘Theme.Dialog’ as theme.




                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Contenu connexe

Tendances

Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART IOXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART IIOXUS 20
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain PointsKen Auer
 

Tendances (7)

Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
25 awt
25 awt25 awt
25 awt
 
GUI programming
GUI programmingGUI programming
GUI programming
 
swingbasics
swingbasicsswingbasics
swingbasics
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain Points
 

En vedette

Интересно о крокодилах
Интересно о крокодилахИнтересно о крокодилах
Интересно о крокодилахchely111chely
 
Music Video Analysis
Music Video AnalysisMusic Video Analysis
Music Video AnalysisCallumHiggins
 
Personalisation for ecommerce
Personalisation for ecommerce Personalisation for ecommerce
Personalisation for ecommerce panarin
 
Ah manifest destiny ch 12
Ah manifest destiny ch 12Ah manifest destiny ch 12
Ah manifest destiny ch 12cmonafu
 
AMERICAN HISTORY Ch.2 Part 1
AMERICAN HISTORY Ch.2 Part 1AMERICAN HISTORY Ch.2 Part 1
AMERICAN HISTORY Ch.2 Part 1cmonafu
 

En vedette (9)

Интересно о крокодилах
Интересно о крокодилахИнтересно о крокодилах
Интересно о крокодилах
 
SA’EY
SA’EYSA’EY
SA’EY
 
Music Video Analysis
Music Video AnalysisMusic Video Analysis
Music Video Analysis
 
Personalisation for ecommerce
Personalisation for ecommerce Personalisation for ecommerce
Personalisation for ecommerce
 
Nc trabajo
Nc trabajoNc trabajo
Nc trabajo
 
Ah manifest destiny ch 12
Ah manifest destiny ch 12Ah manifest destiny ch 12
Ah manifest destiny ch 12
 
Impact auto comp
Impact auto compImpact auto comp
Impact auto comp
 
Creating a logo
Creating a logoCreating a logo
Creating a logo
 
AMERICAN HISTORY Ch.2 Part 1
AMERICAN HISTORY Ch.2 Part 1AMERICAN HISTORY Ch.2 Part 1
AMERICAN HISTORY Ch.2 Part 1
 

Similaire à Android basics – dialogs and floating activities

Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : Creating a dialog Yes/No (english)Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : Creating a dialog Yes/No (english)Bruno Delb
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialogKrazy Koder
 
06 win forms
06 win forms06 win forms
06 win formsmrjw
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Androidma-polimi
 
4.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.15
4.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.154.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.15
4.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.15Rajes Wari
 
Javadocx j option pane
Javadocx j option paneJavadocx j option pane
Javadocx j option paneFarwa Ansari
 
Csphtp1 12
Csphtp1 12Csphtp1 12
Csphtp1 12HUST
 
Visual programming is a type of programming
Visual programming is a type of programmingVisual programming is a type of programming
Visual programming is a type of programmingsanaiftikhar23
 
Windows Forms For Beginners Part 5
Windows Forms For Beginners Part 5Windows Forms For Beginners Part 5
Windows Forms For Beginners Part 5Bhushan Mulmule
 
Gui programming a review - mixed content
Gui programming   a review - mixed contentGui programming   a review - mixed content
Gui programming a review - mixed contentYogesh Kumar
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programmingSynapseindiappsdevelopment
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
The Ring programming language version 1.9 book - Part 82 of 210
The Ring programming language version 1.9 book - Part 82 of 210The Ring programming language version 1.9 book - Part 82 of 210
The Ring programming language version 1.9 book - Part 82 of 210Mahmoud Samir Fayed
 

Similaire à Android basics – dialogs and floating activities (20)

Advance JFACE
Advance JFACEAdvance JFACE
Advance JFACE
 
Android session 3
Android session 3Android session 3
Android session 3
 
Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : Creating a dialog Yes/No (english)Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : Creating a dialog Yes/No (english)
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
06 win forms
06 win forms06 win forms
06 win forms
 
Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
 
Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Android
 
4.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.15
4.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.154.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.15
4.7.14&amp;17.7.14&amp;23.6.15&amp;10.9.15
 
Javadocx j option pane
Javadocx j option paneJavadocx j option pane
Javadocx j option pane
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Csphtp1 12
Csphtp1 12Csphtp1 12
Csphtp1 12
 
Visual programming is a type of programming
Visual programming is a type of programmingVisual programming is a type of programming
Visual programming is a type of programming
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Windows Forms For Beginners Part 5
Windows Forms For Beginners Part 5Windows Forms For Beginners Part 5
Windows Forms For Beginners Part 5
 
Gui programming a review - mixed content
Gui programming   a review - mixed contentGui programming   a review - mixed content
Gui programming a review - mixed content
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programming
 
Controls events
Controls eventsControls events
Controls events
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
The Ring programming language version 1.9 book - Part 82 of 210
The Ring programming language version 1.9 book - Part 82 of 210The Ring programming language version 1.9 book - Part 82 of 210
The Ring programming language version 1.9 book - Part 82 of 210
 

Plus de info_zybotech

Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid drawinfo_zybotech
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorialinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 

Plus de info_zybotech (8)

Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Notepad tutorial
Notepad tutorialNotepad tutorial
Notepad tutorial
 
Java and xml
Java and xmlJava and xml
Java and xml
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 
Applications
ApplicationsApplications
Applications
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 

Dernier

Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Dernier (20)

Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

Android basics – dialogs and floating activities

  • 1. Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 2. Android Basics – Dialogs and Floating Activities As we know android provide Activity class for developing application screens. But many a time application needs to show Dialog boxes or floating screen to do simple tasks likes taking input from user or ask for confirmation etc. In android Dialogs can be created in following 2 ways: 1. Creating a dialog with the help of android Dialog class or its subclass like AlertDialog. 2. Using dialog theme for the activity. Using android Dialog class: Let see how we can create a dialog with the help of Dialog class. To define a dialog the dialog class has to extend the android Dialog class. class MyDialog extends Dialog { /** * @param context */ public MyDialog(Context context) { super(context); } } Define a layout for our dialog. Here is the xml file for of the layout that asks for user’s name. <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/nameMessage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter Name:" > </TextView> <EditText android:id="@+id/nameEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18sp" > </EditText> <LinearLayout A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 3. android:id="@+id/buttonLayout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" > <Button android:id="@+id/okButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="OK" > </Button> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" > </Button> </LinearLayout> </LinearLayout> Use the above layout for our dialog class MyDialog extends Dialog { .... /** * @see android.app.Dialog#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("TestApp", "Dialog created"); setContentView(R.layout.mydialog); } } Now the dialog can be shown by calling the show method like this … MyDialog dialog = new MyDialog(context); dialog.show(); … A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 4. Event handling for the Dialog controls are same as in case of the activity. Modify the dialog code to handle the onclick event on the ok and cancel button. class MyDialog extends Dialog implements OnClickListener { private Button okButton; private Button cancelButton; private EditText nameEditText; protected void onCreate(Bundle savedInstanceState) { okButton = (Button) findViewById(R.id.okButton); cancelButton = (Button) findViewById(R.id.cancelButton); nameEditText = (EditText) findViewById(R.id.nameEditText); okButton.setOnClickListener(this); cancelButton.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()) { case R.id.okButton: dismiss(); break; case R.id.cancelButton: cancel(); break; } } } To close the dialog the dismiss() method can be called. The dialog can call the dismiss method itself or some other code can also close the dialog by calling dismiss(). A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 5. The dialog also supports cancel. Canceling means the dialog action is canceled and does not need to perform any operation. Dialog can be canceled by calling cancel() method. Canceling the dialog also dismisses the dialog. When user clicks the phones BACK button the dialog gets canceled. If you do not want to cancel the dialog on BACK button you can set cancelable to false as setCancelable(false); Note that the cancel() method call till be able to cancel the dialog (which is the desirable functionality in most cases). The dialog’s cancel and dismiss events can be listened with the help of OnCancelListener and OnDismissListener. Returning information from dialog: Now our dialog can take the name from the user. We need to pass that name to the calling activity. Dialog class does not provide any direct method for returning values. But our own Listener can be created as follows: public interface MyDialogListener { public void onOkClick(String name); // User name is provided here. public void onCancelClick(); } The dialog’s constructor has to be modified to take the object of the listener: public MyDialog(Context context, MyDialogListener listener) { super(context); this.listener = listener; } Now the calling activity needs to provide the object of the class that implements the MyDialogListener which will gets called on ok or cancel button clicks. Now we need update the onclick method to return the user name. public void onClick(View view) { switch (view.getId()) { case R.id.okButton: listener.onOkClick(nameEditText.getText().toString()); // returning the user's name. dismiss(); break; case R.id.cancelButton: cancel(); break; } } Using AlertDialog: AlertDialog is the subclass of the Dialog. It by default provide 3 buttons and text message. The buttons can be made visible as required. Following code creates an AlertDialog that ask user a question and provide Yes, No option. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 6. AlertDialog dialog = new AlertDialog.Builder(context).create(); dialog.setMessage("Do you play cricket?"); dialog.setButton("Yes", myOnClickListener); dialog.setButton2("No", myOnClickListener); dialog.show(); The onClick method code for the button listener myOnClickListener will be like this: public void onClick(DialogInterface dialog, int i) { switch (i) { case AlertDialog.BUTTON1: /* Button1 is clicked. Do something */ break; case AlertDialog.BUTTON2: /* Button2 is clicked. Do something */ break; } } AlertDialog.Builder: AlertDialog has a nested class called ‘Builder’. Builder class provides facility to add multichoice or single choice lists. The class also provides methods to set the appropriate Adaptors for the lists, set event handlers for the list events etc. The Builder button calls the Button1, Button2, Button3 as PositiveButton, NeutralButton, NegativeButton. Here is an example of dialog box with Multichoice list new AlertDialog.Builder(context) .setIcon(R.drawable.icon) .setTitle(R.string.alert_dialog_multi_choice) .setMultiChoiceItems(R.array.select_dialog_items, new boolean[]{false, true, false, true, false}, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { /* Something on click of the check box */ } }) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Yes so do some stuff */ } }) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked No so do some stuff */ A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 7. } }) .create(); Activity Managed Dialog: Android also provide facility to create dialogs. Activity created dialog can be managed by Activity methods like showDialog(), onCreateDialog(), onPrepareDialog(), dismissDialog(), removeDialog(). The onCreateDialog create the dialog that needs to be shown, for example /** * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { return new AlertDialog.Builder(this).setMessage("How are you?").setPositiveButton("Fine", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* Do something here */ } }).setNegativeButton("Not so good", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* Do something here */ } }).create(); } You can create multiple dialog boxes and differentiate them with the id parameter. The dialog can be shown with the help of showDialog(id) method. The onCreateDialog method gets called for the first time when showDialog method is called. For subsequent calls to the showDialog() the dialog is not created but shown directly. If you need to update the dialog before it is getting shown then you can do that in onPrepareDialog() method. The methods get called just before the dialog is shown to the user. To close the dialog you can call dismissDialog() method. Generally you will dismiss the dialogs in the click handles of the dialog buttons. The removeDialog() method will remove the dialog from the activity management and if showDialog is again called for that dialog, the dialog needs to be created. Using android Dialog theme for activity: Another simple way to show the dialog is to make the Activity to work as a Dialog (floating activity). This can be done by applying dialog Theme while defining the activity entry in the AndroidManifest.xml A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 8. <activity android:name=”.DialogActivity” android:label=”@string/activity_dialog” android:theme=”@android:style/Theme.Dialog”> … </activity> The activity will be shown as a dialog as the activity is using ‘Theme.Dialog’ as theme. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi