Set Toast Appear Length
I found a solution to this by calling toast.cancel() after a certain delay that is shorter than the standard toast duration.
final Toast toast = Toast.makeText(ctx, "This message will disappear in 1 second", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 1000);
Can an Android Toast be longer than Toast.LENGTH_LONG?
The values of LENGTH_SHORT
and LENGTH_LONG
are 0 and 1. This means they are treated as flags rather than actual durations so I don't think it will be possible to set the duration to anything other than these values.
If you want to display a message to the user for longer, consider a Status Bar Notification. Status Bar Notifications can be programmatically canceled when they are no longer relevant.
How to set Toast display time less than Toast.LENGTH_SHORT
There are only two possible values:
private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds
Setting other values doesn't work. If duration not equals 1 (Toast.LENGTH_LONG
), then duration will be SHORT_DELAY (2 seconds):
long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
In sources of Toast
written that
This time could be user-definable.
but I can't find way to do this.
Update: There is solution here: Set Toast Appear Length
how to increase time of toast msg
If you want to display all toasts one by one, then you need to create a new class and write your own logic. I can give you a solution.
First create a new class as below.
ToastManager.java
class ToastManager {
private final WeakReference<Context> mContext;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private final List<Item> items = new ArrayList<>();
private int durationInMillis;
private boolean isShowing;
private int delayedBetweenToastInMillis;
public ToastManager(Context context) {
mContext = new WeakReference<>(context);
}
public void addToast(String message, @NonNull Duration duration) {
Item item = new Item(message, duration);
items.add(item);
}
public void show() {
// Prevent client from calling this method many time.
if (isShowing) {
return;
}
// Show all toast on screen.
showToast();
// After calling show(), if client add new toasts by calling addToast()
// Then we must show them on screen. Otherwise reset all data of this class.
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!items.isEmpty()) {
showToast();
} else {
reset();
}
}
}, durationInMillis);
}
public void setDelayedBetweenToast(int delayInMillis) {
delayedBetweenToastInMillis = delayInMillis;
}
public void cancel() {
reset();
uiHandler.removeCallbacksAndMessages(null);
}
private void showToast() {
List<Item> list = new ArrayList<>(items);
items.clear();
durationInMillis = 0;
for (Item item : list) {
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext.get(), item.text, item.getDurationForToast()).show();
}
}, durationInMillis);
durationInMillis += item.getDurationInMillis() + delayedBetweenToastInMillis;
}
}
private void reset() {
items.clear();
durationInMillis = 0;
isShowing = false;
}
private static class Item {
String text;
Duration duration;
Item(String text, Duration duration) {
this.text = text;
this.duration = duration;
}
int getDurationForToast() {
return duration == Duration.LENGTH_SHORT ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
}
int getDurationInMillis() {
return duration == Duration.LENGTH_SHORT ? 2000 : 3500;
}
}
enum Duration {
LENGTH_SHORT,
LENGTH_LONG
}
}
Then use it from your class.
NewUserActivity.java
// Create a new instance of ToastManager
ToastManager toastManager = new ToastManager(NewUserActivity.this);
// NAME VALIDATION
if (NAME.isEmpty()) {
toastManager.addToast("Plz Enter Name", ToastManager.Duration.LENGTH_SHORT);
} else if (!((NAME.length() > 3) && (NAME.length() < 15))) {
toastManager.addToast("Name > 3 and < 15", ToastManager.Duration.LENGTH_SHORT);
} else if (!NAME.matches("[a-zA-Z ]+")) {
toastManager.addToast("Only enter alphabets", ToastManager.Duration.LENGTH_SHORT);
}
//EMAIL VALIDATION
if (EMAIL.isEmpty()) {
toastManager.addToast("Plz Enter Email", ToastManager.Duration.LENGTH_SHORT);
} else if (!(EMAIL.matches(emailPattern))) {
toastManager.addToast("Invalid Email", ToastManager.Duration.LENGTH_SHORT);
}
//PHONE NUMBER VALIDATION
if (PHONENO.isEmpty()) {
toastManager.addToast("Plz Enter Phone no.", ToastManager.Duration.LENGTH_SHORT);
} else if (!(PHONENO.length() == 10)) {
toastManager.addToast("Invalid Phone no.", ToastManager.Duration.LENGTH_SHORT);
} else if (!(PHONENO.matches(phonePattern))) {
toastManager.addToast("Invalid Phone Number", ToastManager.Duration.LENGTH_SHORT);
}
//USERNAME VALIDATION
if (username.isEmpty()) {
toastManager.addToast("Plz Enter Username", ToastManager.Duration.LENGTH_SHORT);
} else if (!((username.length() > 6) && (username.length() < 15))) {
toastManager.addToast("Plz Enter Username", ToastManager.Duration.LENGTH_SHORT);
}
//PASSWORD VALIDATION
if (password.isEmpty()) {
toastManager.addToast("Plz Enter Password", ToastManager.Duration.LENGTH_SHORT);
} else if (!((password.length() > 6) && (password.length() < 15))) {
toastManager.addToast("Password > 6 and < 15", ToastManager.Duration.LENGTH_SHORT);
}
// When one or all Edit Text are blank
toastManager.addToast("All fields are compulsory", ToastManager.Duration.LENGTH_SHORT);
// Finally show all toast all screen
toastManager.show();
If you want to set extra time between toast:
toastManager.setDelayedBetweenToast(1000); // 1 second
If you don't want the toast still show when the activity is no longer visible (usually put this line onStop()
method).
@Override
protected void onStop() {
toastManager.cancel();
super.onStop();
}
How can I show a toast for a specific duration?
This cannot be done. To show a toast for a length shorter than Toast.LENGTH_SHORT
, you must cancel it after the time you want. Something like:
final Toast toast = Toast.makeText(getApplicationContext(), "This message will disappear in half a second", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 500);
Set Android Toast duration to be really long (e.g., 1 minute)
Since LENGTH_SHORT is 2 seconds (and LENGTH_LONG is 3.5 seconds), try this:
for (int i=0; i < 30; i++)
{
Toast.makeText(this, "MESSAGE", Toast.LENGTH_SHORT).show();
}
How to change position of Toast in Android?
From the documentation,
Positioning your Toast
A standard toast notification appears near the bottom of the screen,
centered horizontally. You can change this position with the
setGravity(int, int, int)
method. This accepts three parameters: a
Gravity
constant, anx-position
offset, and ay-position
offset.For example, if you decide that the toast should appear in the
top-left corner, you can set the gravity like this:toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
If you want to nudge the position to the right, increase the value of
the second parameter. To nudge it down, increase the value of the last
parameter.
How to display Toast in Android?
In order to display Toast in your application, try this:
Toast.makeText(getActivity(), (String)data.result,
Toast.LENGTH_LONG).show();
Another example:
Toast.makeText(getActivity(), "This is my Toast message!",
Toast.LENGTH_LONG).show();
We can define two constants for duration:
int LENGTH_LONG Show the view or text notification for a long period
of time.int LENGTH_SHORT Show the view or text notification for a short period
of time.
Customizing your toast
LayoutInflater myInflater = LayoutInflater.from(this);
View view = myInflater.inflate(R.layout.your_custom_layout, null);
Toast mytoast = new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();
How to set a duration between two toast?
Your code makes me smile.
OnTouch
events are very fast. It will cause many Toast
to show. Although all Toast are queued up but you will not be able to measure events matched with fired time.
Instead You can use Logs
like this.
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("myClass", "MotionEvent.ACTION_DOWN");
break;
case MotionEvent.ACTION_UP:
Log.d("myClass", "MotionEvent.ACTION_UP");
break;
}
return false;
}
You will get these logs in your Logcat in Android Studio, or press alt+6
Related Topics
How to Use a Library Project in Android Studio
How to Keep a Button as Pressed After Clicking on It
How to Convert Time to " Time Ago " in Android
How to Create a Persistent Alarmmanager
How to Center The Camera So That Marker Is at The Bottom of Screen? (Google Map API V2 Android)
When Using Alertdialog.Builder with Edittext, The Soft Keyboard Doesn't Pop
Evenly Spaced Menu Items on Toolbar
How to Disable "Next" Button on a Edittext Software Keyboard (Replace with "Done" Button)
Handle Screen Orientation Changes When There Are Asynctasks Running
Gradle Warning: Variant.Getoutputfile() and Variant.Setoutputfile() Are Deprecated
How to Launch Android Calendar Application Using Intent (Froyo)
Change Edittext Password Mask Character to Asterisk (*)
Android: Turn Off Screen When Close to Face
Custom Attributes in Android Fragments