What's wrong, really marked red?
here is my Intent
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(this, MainActivity.class);
i.setFlags(268468224);
startActivity(i);
finish();
finishAffinity();
System.exit(0);
}}
i.setFlags(268468224) marker red, any solution?
Only this couple gives us that result :
Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK
for 0x10008000(i.e.268468224)
Android Intent setFlags() has #Retention(RetentionPolicy.SOURCE) annotation.That's why your line i.setFlags(268468224); marked as red because violation of it's rules.
/**
* Set special flags controlling how this intent is handled. Most values
* here depend on the type of component being executed by the Intent,
* specifically the FLAG_ACTIVITY_* flags are all for use with
* {#link Context#startActivity Context.startActivity()} and the
* FLAG_RECEIVER_* flags are all for use with
* {#link Context#sendBroadcast(Intent) Context.sendBroadcast()}.
*
* <p>See the
* <a href="{#docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
* Stack</a> documentation for important information on how some of these options impact
* the behavior of your application.
*
* #param flags The desired flags.
* #return Returns the same Intent object, for chaining multiple calls
* into a single statement.
* #see #getFlags
* #see #addFlags
* #see #removeFlags
*/
public #NonNull Intent setFlags(#Flags int flags) {
mFlags = flags;
return this;
}
#Retention(RetentionPolicy.SOURCE)
public #interface Flags {}
/** #hide */
#IntDef(flag = true, prefix = { "FLAG_" }, value = {
FLAG_FROM_BACKGROUND,
FLAG_DEBUG_LOG_RESOLUTION,
FLAG_EXCLUDE_STOPPED_PACKAGES,
FLAG_INCLUDE_STOPPED_PACKAGES,
FLAG_DEBUG_TRIAGED_MISSING,
FLAG_IGNORE_EPHEMERAL,
FLAG_ACTIVITY_NO_HISTORY,
FLAG_ACTIVITY_SINGLE_TOP,
FLAG_ACTIVITY_NEW_TASK,
FLAG_ACTIVITY_MULTIPLE_TASK,
FLAG_ACTIVITY_CLEAR_TOP,
FLAG_ACTIVITY_FORWARD_RESULT,
FLAG_ACTIVITY_PREVIOUS_IS_TOP,
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
FLAG_ACTIVITY_BROUGHT_TO_FRONT,
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,
FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY,
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET,
FLAG_ACTIVITY_NEW_DOCUMENT,
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET,
FLAG_ACTIVITY_NO_USER_ACTION,
FLAG_ACTIVITY_REORDER_TO_FRONT,
FLAG_ACTIVITY_NO_ANIMATION,
FLAG_ACTIVITY_CLEAR_TASK,
FLAG_ACTIVITY_TASK_ON_HOME,
FLAG_ACTIVITY_RETAIN_IN_RECENTS,
FLAG_ACTIVITY_LAUNCH_ADJACENT,
FLAG_RECEIVER_REGISTERED_ONLY,
FLAG_RECEIVER_REPLACE_PENDING,
FLAG_RECEIVER_FOREGROUND,
FLAG_RECEIVER_NO_ABORT,
FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT,
FLAG_RECEIVER_BOOT_UPGRADE,
FLAG_RECEIVER_INCLUDE_BACKGROUND,
FLAG_RECEIVER_EXCLUDE_BACKGROUND,
FLAG_RECEIVER_FROM_SHELL,
FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS,
})
Related
In my code I have some activities that need some extra parameters (passed as a Bundle in the Intent) to work properly. Some other need none, or have some optional extras.
How to document that in Javadoc?
One way to do that is to define public static method in your Activity to take the extra parameters and return the Intent that you're going to use to start your Activity.
Let's say you have an Activity called MainActivity and it takes an integer id and a String name. here's the code to do it.
public class MainActivity extends Activity {
private static final String BUNDLE_KEY_ID = "id";
private static final String BUNDLE_KEY_NAME = "name";
/**
* Write your documentation here
* #param context Required to create new intent
* #param id write description
* #param name write description
*/
public static Intent getIntent(Context context, int id, String name) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(BUNDLE_KEY_ID, id);
intent.putExtra(BUNDLE_KEY_NAME, name);
return intent;
}
}
In Android Studio ==> Type /** above your Method Signature & Hit Enter
Studio will create documentation basics for that particular method.
/**
*
* #param args1
* #param args2
*/
private void doSomething(int args1,float args2){
}
You just need to add explanation.
/**
* Do something will Blahhh ..Blahhh..
* #param args1 Input argument used to do Blahhh ..Blahhh..
* #param args2 Input argument used to do Blahhh ..Blahhh..
*/
private void doSomething(int args1,float args2){
}
public abstract class SupportAnimator extends Animator {
WeakReference<RevealAnimator> mTarget;
public SupportAnimator(RevealAnimator target) {
mTarget = new WeakReference<>(target);
}
/**
* #return true if using native android animation framework, otherwise is
* nineoldandroids
*/
public abstract boolean isNativeAnimator();
/**
* #return depends from {#link android.os.Build.VERSION} if sdk version
* {#link android.os.Build.VERSION_CODES#LOLLIPOP} and greater will
* return {#link android.animation.Animator}
*/
public abstract Object get();
/**
* Starts this animation. If the animation has a nonzero startDelay, the
* animation will start running after that delay elapses. A non-delayed
* animation will have its initial value(s) set immediately, followed by
* calls to
* {#link android.animation.Animator.AnimatorListener#onAnimationStart(android.animation.Animator)}
* for any listeners of this animator.
*
* <p>
* The animation started by calling this method will be run on the thread
* that called this method. This thread should have a Looper on it (a
* runtime exception will be thrown if this is not the case). Also, if the
* animation will animate properties of objects in the view hierarchy, then
* the calling thread should be the UI thread for that view hierarchy.
* </p>
*
*/
public abstract void start();
/**
* Adds a listener to the set of listeners that are sent events through the
* life of an animation, such as start, repeat, and end.
*
* #param listener
* the listener to be added to the current set of listeners for
* this animation.
*/
public abstract void addListener(AnimatorListener listener);
/**
* Returns whether this Animator is currently running (having been started
* and gone past any initial startDelay period and not yet ended).
*
* #return Whether the Animator is running.
*/
public abstract boolean isRunning();
/**
* Cancels the animation. Unlike {#link #end()}, <code>cancel()</code>
* causes the animation to stop in its tracks, sending an
* {#link AnimatorListener#onAnimationCancel()} to its listeners, followed
* by an {#link AnimatorListener#onAnimationEnd()} message.
*
* <p>
* This method must be called on the thread that is running the animation.
* </p>
*/
public abstract void cancel();
/**
* Ends the animation. This causes the animation to assign the end value of
* the property being animated, then calling the
* {#link AnimatorListener#onAnimationEnd()} method on its listeners.
*
* <p>
* This method must be called on the thread that is running the animation.
* </p>
*/
public void end() {
}
/**
* This method tells the object to use appropriate information to extract
* starting values for the animation. For example, a AnimatorSet object will
* pass this call to its child objects to tell them to set up the values. A
* ObjectAnimator object will use the information it has about its target
* object and PropertyValuesHolder objects to get the start values for its
* properties. A ValueAnimator object will ignore the request since it does
* not have enough information (such as a target object) to gather these
* values.
*/
public void setupStartValues() {
}
/**
* This method tells the object to use appropriate information to extract
* ending values for the animation. For example, a AnimatorSet object will
* pass this call to its child objects to tell them to set up the values. A
* ObjectAnimator object will use the information it has about its target
* object and PropertyValuesHolder objects to get the start values for its
* properties. A ValueAnimator object will ignore the request since it does
* not have enough information (such as a target object) to gather these
* values.
*/
public void setupEndValues() {
}
/**
* Experimental feature
*/
public SupportAnimator reverse() {
if (isRunning()) {
return null;
}
RevealAnimator target = mTarget.get();
if (target != null) {
return target.startReverseAnimation();
}
return null;
}
/**
* <p>
* An animation listener receives notifications from an animation.
* Notifications indicate animation related events, such as the end or the
* repetition of the animation.
* </p>
*/
public interface AnimatorListener {
/**
* <p>
* Notifies the start of the animation.
* </p>
*/
void onAnimationStart();
/**
* <p>
* Notifies the end of the animation. This callback is not invoked for
* animations with repeat count set to INFINITE.
* </p>
*/
void onAnimationEnd();
/**
* <p>
* Notifies the cancellation of the animation. This callback is not
* invoked for animations with repeat count set to INFINITE.
* </p>
*/
void onAnimationCancel();
/**
* <p>
* Notifies the repetition of the animation.
* </p>
*/
void onAnimationRepeat();
}
/**
* <p>
* Provides default implementation for AnimatorListener.
* </p>
*/
public static abstract class SimpleAnimatorListener implements
AnimatorListener {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
#Override
public void onAnimationCancel() {
}
#Override
public void onAnimationRepeat() {
}
}
}
Its an abstract Class and extends by Animator.
and when I use this in next class
if (LOLLIPOP_PLUS) {
return new SupportAnimator(
android.view.ViewAnimationUtils.createCircularReveal(view,
centerX, centerY, startRadius, endRadius),
revealLayout);
}
ObjectAnimator reveal = ObjectAnimator.ofFloat(revealLayout,
CLIP_RADIUS, startRadius, endRadius);
reveal.addListener(new RevealAnimator.RevealFinishedIceCreamSandwich(
revealLayout, layerType));
return new SupportAnimator(reveal, revealLayout);
}
the return new SupportAnimator returns an exception of Cannot instantiate the type SupportAnimator,
its use for Circular Reveal animation and i use this in eclipse, is this suitable to work fine.
Activities are called in this way (an example):
Intent i = new Intent(context, MyActivity.class);
i.putExtra("par1", "value1");
i.putExtra("par2", 2);
startActivityForResult(i);
How can I comment MyActivity class with JavaDoc like methods?
For example in this case:
/**
* This activity show some data
* #param par1 String value of parameter1
* #param par2 int number of records to show
* #return returnValue boolean true if data is showed, false otherwise
*/
to have an idea of which parameters intent expects and what type of return offers.
Just write the JavaDoc part right in top of the class declaration.
/**
* JavaDoc
*/
public class MyActivity {
Right Click on a Method Name-> Source-> Generate Element Comment.
Shortcut
ALT+SHIFT+J
Declare the parameter constants as public static final String and add javadoc field documentation there.
Use #links to bind things together.
Example:
/**
* String containing foo parameter for {#link #XyzzyActivity}
*/
public static final String EXTRA_FOO = "par1";
/**
* XyzzyActivity
*
* Parameters understood: {#link #EXTRA_FOO}, ...
*
* Returns...
*/
Type /** at the top of your method, then press ENTER key. The comment part will become something like this:
/**
*
* #return
*/
You are also allowed to add
#author – who wrote this code
#version – when was it changed
#param – describe method parameters
#return – describe method return values
#throws – describe exceptions thrown
#see – link to other, related items (e.g. “See also…”)
#since – describe when code was introduced (e.g. API Level)
#deprecated - describe deprecated item and what alternative to use instead
I have read about this kind of problem here but the answers don't seem to be working.
I show a Toast when user clicks a button. When the user continously clicks the button the toast keeps on being displayed again and again even when the user exits the activity.
The length of the toast is short. Length of the toast cannot be changed as the text is long.
This is what i have tried as of now:
Toast toast;
toast=Toast.makeText(getApplicationContext(),"text",Toast.LENGTH_SHORT);
if(toast.getView().isShown()==false){
toast.show();
}
This did not work.
I tried :
if(toast.getView().isShown()==true){
toast.cancel();
}
in the onStop(). For some reason the cancel method never works.
If i put the .cancel() before i show the app... then there would be another null check for that. But after doing that also it did not work. I can show a dialog box instead of a toast but that would not be a solution.
Is there any way to check whether a toast is being displayed or not?
For reference
Toast Message in Android
How to avoid a Toast if there's one Toast already being shown
How to prevent Multiple Toast Overlaps
Cancelling an already open toast in Android
The trick is to keep track of the last Toast that was shown, and to cancel that one.
What I have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.
When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).
Here's full code of the Boast wrapper I made - it mimics enough of the Toast methods for me to use it. By default the Boast will cancel the previous one, so you don't build up a queue of Toasts waiting to be displayed.
This code can be found in my Github gist:
mobiRic/Boast
If you just want to know how to cancel the notifications when exiting your app, you will find lots of help in there. If you have improvements or suggestions, please feel free to fork it and get in touch. This is a very old answer, but code has been stable in production on a few apps for some time.
BTW - this should be a direct drop-in replacement for Toast in most use cases.
package mobi.glowworm.lib.ui.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.lang.ref.WeakReference;
/**
* {#link Toast} decorator allowing for easy cancellation of notifications. Use this class if you
* want subsequent Toast notifications to overwrite current ones. </p>
* <p/>
* By default, a current {#link Boast} notification will be cancelled by a subsequent notification.
* This default behaviour can be changed by calling certain methods like {#link #show(boolean)}.
*/
public class Boast {
/**
* Keeps track of certain Boast notifications that may need to be cancelled. This functionality
* is only offered by some of the methods in this class.
* <p>
* Uses a {#link WeakReference} to avoid leaking the activity context used to show the original {#link Toast}.
*/
#Nullable
private volatile static WeakReference<Boast> weakBoast = null;
#Nullable
private static Boast getGlobalBoast() {
if (weakBoast == null) {
return null;
}
return weakBoast.get();
}
private static void setGlobalBoast(#Nullable Boast globalBoast) {
Boast.weakBoast = new WeakReference<>(globalBoast);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Internal reference to the {#link Toast} object that will be displayed.
*/
private Toast internalToast;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Private constructor creates a new {#link Boast} from a given {#link Toast}.
*
* #throws NullPointerException if the parameter is <code>null</code>.
*/
private Boast(Toast toast) {
// null check
if (toast == null) {
throw new NullPointerException("Boast.Boast(Toast) requires a non-null parameter.");
}
internalToast = toast;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Make a standard {#link Boast} that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, CharSequence text, int duration) {
return new Boast(Toast.makeText(context, text, duration));
}
/**
* Make a standard {#link Boast} that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
* #throws Resources.NotFoundException if the resource can't be found.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, int resId, int duration)
throws Resources.NotFoundException {
return new Boast(Toast.makeText(context, resId, duration));
}
/**
* Make a standard {#link Boast} that just contains a text view. Duration defaults to
* {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, CharSequence text) {
return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
}
/**
* Make a standard {#link Boast} that just contains a text view with the text from a resource.
* Duration defaults to {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #throws Resources.NotFoundException if the resource can't be found.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, int resId) throws Resources.NotFoundException {
return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Show a standard {#link Boast} that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
*/
public static void showText(Context context, CharSequence text, int duration) {
Boast.makeText(context, text, duration).show();
}
/**
* Show a standard {#link Boast} that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static void showText(Context context, int resId, int duration)
throws Resources.NotFoundException {
Boast.makeText(context, resId, duration).show();
}
/**
* Show a standard {#link Boast} that just contains a text view. Duration defaults to
* {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
*/
public static void showText(Context context, CharSequence text) {
Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
/**
* Show a standard {#link Boast} that just contains a text view with the text from a resource.
* Duration defaults to {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static void showText(Context context, int resId) throws Resources.NotFoundException {
Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally
* have to call this. Normally view will disappear on its own after the appropriate duration.
*/
public void cancel() {
internalToast.cancel();
}
/**
* Show the view for the specified duration. By default, this method cancels any current
* notification to immediately display the new one. For conventional {#link Toast#show()}
* queueing behaviour, use method {#link #show(boolean)}.
*
* #see #show(boolean)
*/
public void show() {
show(true);
}
/**
* Show the view for the specified duration. This method can be used to cancel the current
* notification, or to queue up notifications.
*
* #param cancelCurrent <code>true</code> to cancel any current notification and replace it with this new
* one
* #see #show()
*/
public void show(boolean cancelCurrent) {
// cancel current
if (cancelCurrent) {
final Boast cachedGlobalBoast = getGlobalBoast();
if ((cachedGlobalBoast != null)) {
cachedGlobalBoast.cancel();
}
}
// save an instance of this current notification
setGlobalBoast(this);
internalToast.show();
}
}
Instead of cancelling the toast. change the text. For Example
Toast t;
t = Toast.makeText(this, "hi", 3000);
t.show();
when you need a different toast then use
t.setText("bye");
t.show();
And If you want to dismiss the toast simply call t.cancel()
You can cancel individual Toasts by calling cancel() on the Toast object. AFAIK, there is no way for you to cancel all outstanding Toasts, though.
Try keeping the timestamp of the last toast, and don't allow any new toasts until a timeout period has elapsed.
Something like:
private static final long TOAST_TIMEOUT_MS = 2000; // tweak this constant
private static long lastToastTime = 0;
public void onButtonClicked() {
long now = System.currentTimeMillis();
if (lastToastTime + TOAST_TIMEOUT_MS < now) {
Toast.makeText(...).show();
lastToastTime = now;
}
}
I wouldn't worry about a single toast sticking around for a second after the user exits the app -- this is a pretty standard behavior.
I've been using a common "myToast" which I use "myToast.cancel() prior to issuing a new toast. For Android v2.3 and older, this works great. When a new toast needs to be sent, the old one, if still on-screen, is canceled (and disappears immediately) to be replaced with the new toast. This avoids stacking up a bunch of toasts if the user presses a key multiple times that needs the alert (and other conditions). My actual case is one toast appears when a wrong key is pressed, and another appears if the Clear key is not pressed.
For Android 4.0 and 4.1, issuing a myToast.cancel() before the next toast kills both the current and the next toast. The current cancel() API does indicate it cancels the current AND the next toast (which seems rather stupid). Why cancel a toast you want to put up?
Any ideas on making cancel work consistently across Android versions (and the way it works in v2.3 and older)?
I'll try some inelegant dual toast system with tracking for which toast is in use, but it seems such a pain work around this bad behavior in 4.x to get what works perfectly and logically in older Android versions.
Ok, I solved it, but it's not nearly as clean as I would have liked. I implemented a dual toast approach, where it alternates between two toasts. First we define the toasts for the activity prior to the OnCreate:
Toast toast0;
Toast toast1;
private static boolean lastToast0 = true;
In the OnCreate:
toast0 = new Toast(getApplicationContext());
toast0.cancel();
toast1 = new Toast(getApplicationContext());
toast1.cancel();
And finally, when I need to display the toast and cancel the prior toast at the same time I use something similar to:
if (lastToast0) {
toast0.cancel();
toast1.setDuration(Toast.LENGTH_LONG);
toast1.setText("new message");
toast1.show();
lastToast0 = false;
} else {
toast1.cancel();
toast0.setDuration(Toast.LENGTH_LONG);
toast0.setText("new message");
toast0.show();
lastToast0 = true;
}
If you need to just cancel an existing toast (before it times out) use:
toast0.cancel();
toast1.cancel();
Tested on Nexus 7 (4.1), Emulator 4.0, and several devices with Android 2.2, 2.3.
Instead of calling cancel(). Try resetting the text and call show(). This should cancel the last toast by itself
myToast.setText("wrong key")
myToast.show();
If you keep using the same myToast instead of creating one every time I guess they won't stack up.
Did nandeesh's solution not work for you?
His solution would be cleaner than using two different toasts.
For example, (expanding on his/her answer) prior to onCreate we'd declare the toast:
private Toast myToast;
and in onCreate we'd have to initialize it using makeToast (otherwise we'd get an error):
myToast = Toast.makeText(getApplicationContext(), null, Toast.LENGTH_SHORT);
and whenever we want a toast to be shown we'd simply call:
myToast.setText("some text");
myToast.show();
and this would replace the previous toast properly.
Here is my answer copied from another similar question here:
Android cancel Toast when exiting the app and when toast is being shown
The Boast class accomplishes exactly what you need.
The trick is to keep track of the last Toast that was shown, and to cancel that one.
What I have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.
When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).
Here's full code of the Boast wrapper I made - it mimics enough of the Toast methods for me to use it. By default the Boast will cancel the previous one, so you don't build up a queue of Toasts waiting to be displayed.
If you just want to know how to cancel the notifications when exiting your app, you will find lots of help in there.
package mobi.glowworm.lib.ui.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.lang.ref.WeakReference;
/**
* {#link Toast} decorator allowing for easy cancellation of notifications. Use this class if you
* want subsequent Toast notifications to overwrite current ones. </p>
* <p/>
* By default, a current {#link Boast} notification will be cancelled by a subsequent notification.
* This default behaviour can be changed by calling certain methods like {#link #show(boolean)}.
*/
public class Boast {
/**
* Keeps track of certain Boast notifications that may need to be cancelled. This functionality
* is only offered by some of the methods in this class.
* <p>
* Uses a {#link WeakReference} to avoid leaking the activity context used to show the original {#link Toast}.
*/
#Nullable
private volatile static WeakReference<Boast> weakBoast = null;
#Nullable
private static Boast getGlobalBoast() {
if (weakBoast == null) {
return null;
}
return weakBoast.get();
}
private static void setGlobalBoast(#Nullable Boast globalBoast) {
Boast.weakBoast = new WeakReference<>(globalBoast);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Internal reference to the {#link Toast} object that will be displayed.
*/
private Toast internalToast;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Private constructor creates a new {#link Boast} from a given {#link Toast}.
*
* #throws NullPointerException if the parameter is <code>null</code>.
*/
private Boast(Toast toast) {
// null check
if (toast == null) {
throw new NullPointerException("Boast.Boast(Toast) requires a non-null parameter.");
}
internalToast = toast;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Make a standard {#link Boast} that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, CharSequence text, int duration) {
return new Boast(Toast.makeText(context, text, duration));
}
/**
* Make a standard {#link Boast} that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
* #throws Resources.NotFoundException if the resource can't be found.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, int resId, int duration)
throws Resources.NotFoundException {
return new Boast(Toast.makeText(context, resId, duration));
}
/**
* Make a standard {#link Boast} that just contains a text view. Duration defaults to
* {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, CharSequence text) {
return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
}
/**
* Make a standard {#link Boast} that just contains a text view with the text from a resource.
* Duration defaults to {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #throws Resources.NotFoundException if the resource can't be found.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, int resId) throws Resources.NotFoundException {
return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Show a standard {#link Boast} that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
*/
public static void showText(Context context, CharSequence text, int duration) {
Boast.makeText(context, text, duration).show();
}
/**
* Show a standard {#link Boast} that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static void showText(Context context, int resId, int duration)
throws Resources.NotFoundException {
Boast.makeText(context, resId, duration).show();
}
/**
* Show a standard {#link Boast} that just contains a text view. Duration defaults to
* {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
*/
public static void showText(Context context, CharSequence text) {
Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
/**
* Show a standard {#link Boast} that just contains a text view with the text from a resource.
* Duration defaults to {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static void showText(Context context, int resId) throws Resources.NotFoundException {
Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally
* have to call this. Normally view will disappear on its own after the appropriate duration.
*/
public void cancel() {
internalToast.cancel();
}
/**
* Show the view for the specified duration. By default, this method cancels any current
* notification to immediately display the new one. For conventional {#link Toast#show()}
* queueing behaviour, use method {#link #show(boolean)}.
*
* #see #show(boolean)
*/
public void show() {
show(true);
}
/**
* Show the view for the specified duration. This method can be used to cancel the current
* notification, or to queue up notifications.
*
* #param cancelCurrent <code>true</code> to cancel any current notification and replace it with this new
* one
* #see #show()
*/
public void show(boolean cancelCurrent) {
// cancel current
if (cancelCurrent) {
final Boast cachedGlobalBoast = getGlobalBoast();
if ((cachedGlobalBoast != null)) {
cachedGlobalBoast.cancel();
}
}
// save an instance of this current notification
setGlobalBoast(this);
internalToast.show();
}
}
Make a java class as ShowToast.java like below
public class ShowToast {
private static Toast toast;
public static void show(Context mcontext, String text) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(mcontext, text, Toast.LENGTH_SHORT);
toast.show();
}
}
Then call it as
ShowToast.show(getApplicationContext(),"YOUR_TOAST_TEXT");
cancel() doesn't do anything I'm afraid.
I would suggest using Crouton https://github.com/keyboardsurfer/Crouton
This my solution works perfect both for 4.* and 2.3 Android versions
static Toast toast;
.....
if (toast != null)
toast.cancel();
boolean condition = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
if ((toast == null && condition) || !condition)
toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
if ((toast != null && condition))
toast.setText(text);
toast.show();
Create an Toast Object:
Toast toastobject=null;
Now use the below code to display the toast. This will work find for me
int index = clickCounter-1;
if(toastobject!= null)
{
toastobject.cancel();
}
toastobject = Toast.makeText(this,"Toast Text" , Toast.LENGTH_SHORT);
listItems.remove(index);
toastobject.show();
create new function and call this.
ImageButton ABtn = (ImageButton) findViewById(R.id.Btn);
ABtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
SETToast("mytext");
}
});
private Toast toast = null;
public void SETToast( String text)
{
if(toast==null)
{
toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast=null;
}
}, 2000);
}
else
{
toast.setText(text);
}
}
Kotlin approach:
class MyActivity: Activity {
private var toast: Toast? = null
fun yourFunction() {
toast?.cancel()
toast = if(documentWasSaved) {
makeText(this, "Document was saved"), Toast.LENGTH_LONG)
} else {
makeText(this, "Failed to save your document", Toast.LENGTH_LONG)
}
toast?.show()
}
}