0% found this document useful (0 votes)
99 views

4 Android Toast and Dialog PDF

1. The document discusses Android Toast and Dialog. It describes Toast as a simple popup message that provides feedback without blocking the user interface. Dialog is more complex and blocks user interaction until closed. 2. It provides code examples for creating a basic Toast, positioning Toasts on screen, and creating a custom Toast layout. Creating a Dialog requires setting up the Dialog view hierarchy and managing its lifecycle. 3. The document aims to teach how to utilize Android Toast and Dialog popups to provide feedback or request input from users.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

4 Android Toast and Dialog PDF

1. The document discusses Android Toast and Dialog. It describes Toast as a simple popup message that provides feedback without blocking the user interface. Dialog is more complex and blocks user interaction until closed. 2. It provides code examples for creating a basic Toast, positioning Toasts on screen, and creating a custom Toast layout. Creating a Dialog requires setting up the Dialog view hierarchy and managing its lifecycle. 3. The document aims to teach how to utilize Android Toast and Dialog popups to provide feedback or request input from users.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT 4: Controlling The Views

LESSON 5:
ANDROID TOAST AND DIALOG

DURATION:
▪ 30 Minutes

OBJECTIVES:

At the end of this lesson, you should be able to:


▪ Utilize the Android Toast and Dialog;

▪ Apply the features of Toast and Dialog; and

▪ Demonstrate how to use Toast and Dialog.

IT 413: WIRELESS AND MOBILE TECHNOLOGY 338


ASSESS YOURSELF
UNIT 4: Controlling The Views

The image below is an Android Dialog. Can you identify each of the parts labeled
with numbers and its functions?

1. _______________________ 2. _______________________

3. _______________________

IT 413: WIRELESS AND MOBILE TECHNOLOGY 339


UNIT 4: Controlling The Views

ANDROID TOAST

What is an Android Toast?


A toast gives straightforward feedback message about an operation in a little popup.
It only fills the amount of space required for the message and the current activity
remains visible and interactive. Toasts naturally vanish after a timeout.

Figure 5.1.1 Simple Toast Message

Toasts are not clickable. In the event that user response to a status message is
required, consider instead using a Notification.

The Basics
First, instantiate a Toast object with one of the makeText() methods. This method
takes three parameters: the application Context, the text message, and the duration
for the toast. It returns a properly initialized Toast object. You can display the toast
notification with show(), as shown in the following example:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);


toast.show();

This example illustrates everything you would like for most toast notifications. You
should seldom require anything else. You will, however, need to position the
toast differently or indeed utilize your own format rather
than a straightforward content message.
The following sections describe how you'lldo these things.
You can moreover chain your methods and avoid holding on to the Toast object, like
this:

Context context = getApplicationContext();

IT 413: WIRELESS AND MOBILE TECHNOLOGY 340


UNIT 4: Controlling The Views

Do not use the public constructor for a Toast unless you are going to define the layout
with setView(View). If you do not have a custom layout to use, you must use
makeText(Context, int, int) to create the Toast.

Toast Syntax

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

Substitute the values:


Toast.makeText(MainActivity.this, "Details Saved Successfully.", Toast.LENGTH_SHORT).show();

Positioning your Toast


A standard toast notification shows up near the bottom of the screen, centered
horizontally. You'll be able change this position with the setGravity(int, int, int) method.
This accepts three parameters: a Gravity constant, an x-position offset, and a y-
position offset.

Figure 5.1.2 Standard Simple Toast position

IT 413: WIRELESS AND MOBILE TECHNOLOGY 341


UNIT 4: Controlling The Views

If there is a need to set position of a Toast message, then setGravity() method can
be used.

public void setGravity (int gravity,


int xOffset,
int yOffset)
Parameters: This method accepts three parameters:
gravity: This sets the position of the Toast message. Following constants can be used
to specify the position of a Toast:
1. TOP
2. BOTTOM
3. LEFT
4. RIGHT
5. CENTER
6. CENTER_HORIZONTAL
7. CENTER_VERTICAL

Each constant indicates the position in X and Y pivot, except CENTER constant which
sets position centered for both horizontal and vertical direction.
xOffset: This is the offset value that tells how much to shift the Toast message
horizontally on the x axis.
yOffset: This is the offset value that tells how much to shift the Toast message
vertically on the y axis.

For example, if you decide that the toast should appear in the bottom-right corner, you
can set the gravity like this:

toast.setGravity(Gravity.BOTTOM|Gravity.RIGHT, 0, 0);

1. To display the Toast at the center:


toast.setGravity(Gravity.CENTER, 0, 0);
2. To display the Toast at the top, centered horizontally:
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 0);

3. To display the Toast at the top, centered horizontally, but 30 pixels down from
the top:
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 30);
4. To display the Toast at the bottom, rightmost horizontally:
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);

IT 413: WIRELESS AND MOBILE TECHNOLOGY 342


UNIT 4: Controlling The Views

Figure 5.1.3 Positioned Toast Message

Sample code:

package org.geeksforgeeks.positionedToast_Example;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

// Defining the object for button


Button btn;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Binding the components to their respective objects
// by assigning their IDs
// with the help of findViewById() method

Button btn = (Button)findViewById(R.id.Button01);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)

IT 413: WIRELESS AND MOBILE TECHNOLOGY 343


UNIT 4: Controlling The Views

{
// Displaying posotioned Toast message
Toast t = Toast.makeText(getApplicationContext(),
"This a
positioned toast message",

Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
t.show();
}
});
}
}

If you want to nudge the position to the left, increase the value of the second
parameter. To nudge it up, increase the value of the last parameter.

Creating a Custom Toast View


In the event that a simple text message isn't enough, you'll be able make a customized
layout for your toast notification. To form a custom format, define a View layout, in
XML or in your application code, and pass the root View object to the setView(View)
method.
The following snippet contains a customized layout for a toast notification (saved
as layout/custom_toast.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
/>
</LinearLayout>

Notice that the ID of the LinearLayout element is "custom_toast_container". You must


use this ID and the ID of the XML layout file "custom_toast" to inflate the layout, as
shown here:

LayoutInflater inflater = getLayoutInflater();


View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_container));

IT 413: WIRELESS AND MOBILE TECHNOLOGY 344


UNIT 4: Controlling The Views

TextView text = (TextView) layout.findViewById(R.id.text);


text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());


toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and


after that inflate the layout from XML utilizing inflate(int, ViewGroup). The first
parameter is the layout resource ID and the second is the root View. You'll be able
utilize this inflated layout to discover more View objects within the layout, so now
capture and define the content for the ImageView and TextView elements. Finally,
make a new Toast with Toast(Context) and set some properties of the toast, such as
the gravity and duration. At that point call setView(View) and pass it the inflated layout.
You can now display the toast along with your custom layout by calling show().

Toast class
Toast class gives a basic popup message that's shown on the current activity UI
screen (e.g. Main Activity).

Constants of Toast class:


CONSTANTS DESCRIPTION
public static final int LENGTH_LONG displays for a long time

public static final intLENGTH_SHORT displays for a short time

Methods of Toast class


METHODS DESCRIPTION
public static Toast makeText(Context makes the toast message consisted of
context, CharSequence text, int text and time duration
duration)
public void show() displays a toast message

public void setMargin (float changes the horizontal and vertical


horizontalMargin, float verticalMargin) differences

What is a Context?
Interface to global information about an application environment. This is an abstract
class whose implementation is provided by the Android system. It allows access to
application-specific resources and classes, as well as up-calls for application-level
operations such as launching activities, broadcasting and receiving intents, etc.

IT 413: WIRELESS AND MOBILE TECHNOLOGY 345


UNIT 4: Controlling The Views

Understanding Context by a Real World Example


Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a reasonable
time. But for these things there are too numerous other things, he needs to do during
the time of stay. So how does he get these things? He will inquire the room-service
person to bring these things for him. Right? So here the room-service person is the
context considering you're the single activity and the hotel to be your app, finally, the
breakfast, lunch & supper have to be the resources

How Does This Work?

1. It is the context of the current/active state of the application.


Usually, the app got multiple screens like display/inquiry/add/delete
screens(General requirement of a basic app). So when the user is searching for
something, the context is an inquiry screen in this case.

2. It is used to get information about the activity and application.


The inquiry screen’s context specifies that the user is in inquiry activity, and he/she
can submit queries related to the app.

3. It is used to get access to resources, databases, and shared preferences,


etc.
Via Rest services, API calls can be consumed in android apps. Rest Services
usually hold database data and provide the output in JSON format to the android
app. The context for the respective screen helps to get hold of database data and
the shared data across screens.

4. Both the Activity and Application classes extend the Context class.
In android, context is the main important concept and the wrong usage of it leads
to memory leakage. Activity refers to an individual screen and Application refers to
the whole app and both extend the context class.

Types of Context in Android

There are mainly two types of context are available in Android.


1. Application Context and
2. Activity Context

The Overall view of the App hierarchy looks like the following:

IT 413: WIRELESS AND MOBILE TECHNOLOGY 346


UNIT 4: Controlling The Views

Figure 5.2.1 Overall View of the App Hierarchy

Application Context
This context is tied to the life cycle of an application. Mainly it is an instance that is
a singleton and can be accessed via getApplicationContext(). Some use cases of
Application Context are:

• If it is necessary to create a singleton object


• During the necessity of a library in an activity

getApplicationcontext()

It is utilized to return the context which is connected to the Application which holds
all activities running inside it. When we call a method or a constructor, we often
have to be pass a setting and frequently we utilize “this” to pass the activity setting
or “getApplicationContext” to pass the application context. This method is for the
most part used for the application level and can be used to refer to all the exercises.
For example, in case we want to get to a variable all through the android app, one
should utilize it by means of getApplicationContext().

Ex.
import android.app.Application;

public class GlobalExampleClass extends Application


{
private String globalName;
private String globalEmail;

public String getName()


{
return globalName;
}

public void setName(String aName)


{
globalName = aName;
}

public String getEmail()


{
return globalEmail;
}

public void setEmail(String aEmail)


{
globalEmail = aEmail;
}
}

IT 413: WIRELESS AND MOBILE TECHNOLOGY 347


UNIT 4: Controlling The Views

Activity Context

It is the activity context meaning each and every screen got an activity. For example,
EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity as
it were. It is tied to the life cycle of activity. It is utilized for the current context. The
method of invoking the Activity Context is getContext().

Some use cases of Activity Context are:

The user is creating an object whose lifecycle is attached to an activity.


Whenever inside an activity for UI related kind of operations like toast, dialogue,
etc.,
getContext():
It returns the Context which is linked to the Activity from which it is called. This is
useful when we want to call the context from only the current running activity.

Ex.

@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
....
// view.getContext() refers to the current activity view
// Here it is used to start the activity
Intent intent = new Intent(view.getContext(), <your java classname>.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}

List of functionalities of Activity Context:

• Load Resource Values


• Layout Inflation
• Start an Activity
• Show a Dialog
• Start a Service
• Bind to a Service
• Send a Broadcast
• Register BroadcastReceiver

IT 413: WIRELESS AND MOBILE TECHNOLOGY 348


UNIT 4: Controlling The Views

ANDROID DIALOG

What is a Dialog?

A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events
that require users to take an action before they can proceed.

Figure 5.4.1 Alert Dialog

The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog
directly. Instead, use one of the following subclasses:
AlertDialog - A dialog that can show a title, up to three buttons, a list of selectable
items, or a custom layout.
DatePickerDialog or TimePickerDialog - A dialog with a pre-defined UI that allows
the user to select a date or time.
These classes characterize the style and structure for your dialog, but you ought to
utilize a DialogFragment as a holder for your dialog. The DialogFragment class
provides all the controls you need to create your dialog and oversee its appearance,
rather than calling methods on the Dialog object.
Using DialogFragment to oversee the dialog guarantees that it accurately handles
lifecycle events such as when the user presses the Back button or rotates the screen.
The DialogFragment class moreover permits you to reuse the dialog's UI as an
embeddable component in a bigger UI, just like a traditional Fragment (such as when
you need the dialog UI to appear differently on large and small screens).

If you want a custom dialog, you can instead display an Activity as a dialog instead of
using the Dialog APIs. Simply create an activity and set its theme
to Theme.Holo.Dialog in the <activity> manifest element

IT 413: WIRELESS AND MOBILE TECHNOLOGY 349


UNIT 4: Controlling The Views

Creating a Dialog Fragment


You'll be able finish a wide variety of dialog designs—including custom layouts and
those described within the Dialogs design guide—by expanding DialogFragment and
making an AlertDialog within the onCreateDialog() callback method.
For example, here's a basic AlertDialog that's managed within a DialogFragment:

public class FireMissilesDialogFragment extends DialogFragment {


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}

Figure 5.4.2 A dialog with a message and two action buttons.

Building an Alert Dialog


The AlertDialog class permits you to build a variety of dialog designs and is frequently
the only dialog class you'll need. As appeared in figure 5.4.3, there are three regions
of an alert dialog:

IT 413: WIRELESS AND MOBILE TECHNOLOGY 350


UNIT 4: Controlling The Views

Figure 5.4.3 The layout of a Dialog.

Title
This is often optional and ought to be utilized as it were when the content region is
occupied by a detailed message, a list, or custom layout. In case you need to state a
simple message or question (such as the dialog in figure 5.4.3), you do not need a
title.
Content Area
This can display a message, a list, or other custom layout.
Action Buttons
There should be no more than three action buttons in a dialog.

The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog
with these kinds of content, including a custom layout.

// 1. Instantiate an <code><a
href="/reference/android/app/AlertDialog.Builder.html">AlertDialog.Build
er</a></code> with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// 2. Chain together various setter methods to set the dialog


characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);

// 3. Get the <code><a


href="/reference/android/app/AlertDialog.html">AlertDialog</a></code>
from <code><a
href="/reference/android/app/AlertDialog.Builder.html#create()">create()
</a></code>
AlertDialog dialog = builder.create();

By default, touching a list item dismisses the dialog, unless you're using one of the
following persistent choice lists.

IT 413: WIRELESS AND MOBILE TECHNOLOGY 351


UNIT 4: Controlling The Views

Adding buttons

To add action buttons like those in figure 5.4.3, call the setPositiveButton() and
setNegativeButton() methods:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());


// Add the buttons
builder.setPositiveButton(R.string.ok, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Set other dialog properties
...

// Create the AlertDialog


AlertDialog dialog = builder.create();

The set...Button() methods require a title for the button (supplied by a string resource)
and a DialogInterface.OnClickListener that defines the action to take when the user
presses the button.

There are three different action buttons you can add:

Positive
You should use this to accept and continue with the action (the "OK" action).

Negative
You should use this to cancel the action.

Neutral
You should use this when the user may not want to proceed with the action, but doesn't
necessarily want to cancel. It appears between the positive and negative buttons. For
example, the action might be "Remind me later."

You can add only one of each button type to an AlertDialog. That is, you cannot have
more than one "positive" button.

Alert Dialog Syntax


AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Alert")
.setMessage("Are you sure, you want to continue ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener()

As for the syntax of Alert Dialog, see the image below and substitute the values for the
three regions of the Alert Dialog (Title, Action Buttons Content Area).

IT 413: WIRELESS AND MOBILE TECHNOLOGY 352


UNIT 4: Controlling The Views

Figure 5.4.4 The layout of a Dialog with the three regions.

And you’ll be able to create a simple Alert Dialog in android.

IT 413: WIRELESS AND MOBILE TECHNOLOGY 353

You might also like