4 Android Toast and Dialog PDF
4 Android Toast and Dialog PDF
LESSON 5:
ANDROID TOAST AND DIALOG
DURATION:
▪ 30 Minutes
OBJECTIVES:
The image below is an Android Dialog. Can you identify each of the parts labeled
with numbers and its functions?
1. _______________________ 2. _______________________
3. _______________________
ANDROID TOAST
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;
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:
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
If there is a need to set position of a Toast message, then setGravity() method can
be used.
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);
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);
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;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// 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.
Toast class
Toast class gives a basic popup message that's shown on the current activity UI
screen (e.g. Main Activity).
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.
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.
The Overall view of the App hierarchy looks like the following:
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:
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;
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().
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);
}
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.
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
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());
By default, touching a list item dismisses the dialog, unless you're using one of the
following persistent choice lists.
Adding buttons
To add action buttons like those in figure 5.4.3, call the setPositiveButton() and
setNegativeButton() methods:
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.
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.
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).