Updating the text of a Toast without waiting for it to disappear

Asked

Viewed 222 times

2

I’m creating an app for testing and I’m using toasts to validate my tests. I usually define a Toast as follows:

Toast.makeText(this, "Texto que eu quero que apareça",Toast.LENGTH_SHORT).show();

Is there any way to change the text of a Toast while it is still being displayed?

When I try to just send another Toast be shown, the first Toast needs to disappear before the other appears, I would like to know how to change that.

1 answer

4


According to the reference: http://developer.android.com/reference/android/widget/Toast.html.

The static makeText method returns the created Toast object, I believe that if you save the reference to the object and use the setText method in time for it to still be visible, the text is changed. If it doesn’t work, you can cancel (instantaneously) Toast with the Cancel method and generate a new one with the new text.

Code example:

public class MyActivity extends Activity {
    Toast mToast;

    public void showToast(String text) {
        if (mToast == null) {
            mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        }
        mToast.setText(text);
        mToast.cancel();
        mToast.show();
    }
}
  • Could you give me an example of how to define Toast without being statically? I tried but failed.

  • You could save it as a local variable in your class (Activity or Fragment) and reuse it. The example below is more generic, because it is not possible to know if Toast is still visible. 

public class MyActivity extends Activity {
 Toast mToast;

 public void showToast(String text) {
 if(mToast == null) {
 mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
 }
 mToast.setText(text); mToast.Cancel(); mToast.show(); } } Or you can use the Supertoast library (https://github.com/JohnPersano/SuperToasts), which is very versatile.

  • 1

    @Wakim It would be good if you edit your reply to include the code of your last comment. The answer gets better (and potentially more useful), and the code gets more readable. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.