0

I want to increase the duration of toast msg.I tried some code from some sites and also saw some yt videos but still the prob isn't solved.On clicking the button it displays the toast msg all at a time but i want it to display one by one on some time duration. Also I want to show toast msg that" all fields are compulsory" when even one or all edittexts are blank

public class NewUserActivity extends AppCompatActivity {


    EditText name;
    EditText email;
    EditText phone;
    EditText usname;
    EditText passsword;
    Button register;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_user_login);


        name = (EditText) findViewById(R.id.name);
        email = (EditText) findViewById(R.id.email);
        phone = (EditText) findViewById(R.id.phone);
        usname = (EditText) findViewById(R.id.usname);
        passsword = (EditText) findViewById(R.id.passsword);
        register= (Button) findViewById(R.id.register);


        register.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String NAME = name.getText().toString().trim();
                String EMAIL = email.getText().toString().trim();
                String PHONENO =phone.getText().toString().trim();
                String username = usname.getText().toString().trim();
                String password = passsword.getText().toString().trim();
                String emailPattern = "^[a-zA-Z0-9+_.-]{3,32}+@[a-zA-Z0-9.-]{2,32}+$";
                String phonePattern = "(0/91)?[7-9][0-9]{9}";


                // NAME VALIDATION
                if(NAME.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Plz Enter Name",Toast.LENGTH_SHORT).show();
                }else if( !((NAME.length() > 3) && (NAME.length() < 15)) ){
                    Toast.makeText(getApplicationContext(),"Name > 3 and < 15",Toast.LENGTH_SHORT).show();
                }else if(!NAME.matches("[a-zA-Z ]+")){
                    Toast.makeText(getApplicationContext(),"Only enter alphabets",Toast.LENGTH_SHORT).show();
                }

                //EMAIL VALIDATION
                if(EMAIL.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Plz Enter Email",Toast.LENGTH_SHORT).show();
                }else if(!(EMAIL.matches(emailPattern))){
                    Toast.makeText(getApplicationContext(),"Invalid Email",Toast.LENGTH_SHORT).show();
                }

               //PHONE NUMBER VALIDATION
                if(PHONENO.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Plz Enter Phone no.",Toast.LENGTH_SHORT).show();
                }else if(!(PHONENO.length()==10)){
                    Toast.makeText(getApplicationContext(),"Invalid Phone no.",Toast.LENGTH_SHORT).show();}
                 else if(!(PHONENO.matches(phonePattern))){
                        Toast.makeText(getApplicationContext(),"Invalid Phone Number",Toast.LENGTH_SHORT).show();
                }

                //USERNAME VALIDATION
                if(username.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Plz Enter Username",Toast.LENGTH_SHORT).show();
                }else if(!((username.length() > 6) && (username.length() < 15))){
                    Toast.makeText(getApplicationContext(),"Username > 6 and < 15",Toast.LENGTH_SHORT).show();
                }

               //PASSWORD VALIDATION
                if(password.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Plz Enter Password",Toast.LENGTH_SHORT).show();
                }else if(!((password.length() > 6) && (password.length() < 15))){
                    Toast.makeText(getApplicationContext(),"Password > 6 and < 15",Toast.LENGTH_SHORT).show();
                }





            }
        });


    }


}
sank
  • 133
  • 7
  • Does this answer your question? [Can an Android Toast be longer than Toast.LENGTH\_LONG?](https://stackoverflow.com/questions/2220560/can-an-android-toast-be-longer-than-toast-length-long) – fdermishin Nov 21 '20 at 19:52
  • No,I want to set the time duration of toast message – sank Nov 21 '20 at 19:54
  • Actually, for what you are using toasts for (showing validation errors for user input) it would be much better to show the error(s) below the input fields with EditText.setError() or using TextInputLayout plus TextInputEditText. – Ridcully Nov 22 '20 at 06:15

2 Answers2

2

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();
}
Son Truong
  • 13,661
  • 5
  • 32
  • 58
  • Also I want to show toast msg that" all fields are compulsory" when even one or all edittexts are blank.Can u please help me out with this. – sank Nov 23 '20 at 14:04
  • You have 5 EditText, so you can create an int variable named totalBlankEditText = 0. For each condition isEmpty(), you increase its value by one. At the end just check condition. If (totalBlankEditText == 1 || totalBlankEditText == 5) {// Show all fields are compulsory}. – Son Truong Nov 23 '20 at 14:13
  • Thank u ...I will try this. – sank Nov 23 '20 at 14:22
  • error: constructor Handler in class Handler cannot be applied to given types; private final Handler uiHandler = new Handler(Looper.getMainLooper()) { ^ required: no arguments found: Looper reason: actual and formal argument lists differ in length i am getting this error – sank Nov 23 '20 at 14:43
  • Why do you want to modify the ToastManager class, is there any reason? – Son Truong Nov 23 '20 at 14:51
  • No i dont want to modity ..but while implementing the code this error has arised. – sank Nov 23 '20 at 14:53
  • It seems like you have a syntax error such as forget { or } symbol. You can create a new class named ToastManager and copy my code into it. – Son Truong Nov 23 '20 at 14:58
  • I guess you import wrong Handler class. Go to the top of the ToastManager class. Make sure you import android.os.Handler instead of java.util.logging.Handler – Son Truong Nov 23 '20 at 15:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224988/discussion-between-son-truong-and-sank). – Son Truong Nov 23 '20 at 15:11
  • Oh yes right i imported java.util.logging.Handler I will make changes – sank Nov 23 '20 at 15:11
1

You can use Toast.LENGTH_LONG to make it longer.

As far as I know, there is no option to set a specific time to show the toast. The times for the toasts are below:

int LENGTH_SHORT = 2000; // 2 seconds
int LENGTH_LONG = 3500; // 3.5 seconds

You could go around this by adding the values together.

For Example:

Toast.makeText(this, "Hello World!", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Hello World!", Toast.LENGTH_LONG).show();

To get a toast of a total length of 7 seconds because 3.5s + 3.5s = 7s

user14678216
  • 2,886
  • 2
  • 16
  • 37