Вопрос

I have an activity in which i'm planing to use a toast message for information. The toast contains a large text, i used this, it is not working.

Toast.makeText
(getApplicationContext(), "My Text Goes Here", 20000).show();
Это было полезно?

Решение

That's not possible. The last parameter in the makeText method actually expects one of two constants:

Toast.LENGTH_LONG

and

Toast.LENGTH_SHORT

You cannot influence how long the toast is shown aside from choosing one of these. If you have a long text consider using a dialog like this:

AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Title");
builder.setMessage("Long Text...");
builder.setNeutralButton("Ok",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
AlertDialog alert = builder.create();
alert.show();

Of course you should not hardcode strings like I did in this example. Consider putting them in the string resources.

Другие советы

The values of LENGTH_SHORT and LENGTH_LONG are 0 and 1.They are treated as flags rather than actual durations so it is not possible to set the duration to anything other than these values.

Forget about the Toast and go for Dialog.

Personally I prefer to create a general method (in a separate Java object called as needed) for creating Dialogs, to avoid code duplication.

public void showAlert(int title, int message, Activity reportActivity) {
        // Create an alert dialog box
        AlertDialog.Builder builder = new AlertDialog.Builder(reportActivity);
        // Set alert title
        builder.setTitle(title);

        // Set the value for the positive reaction from the user
        // You can also set a listener to call when it is pressed
        builder.setPositiveButton(R.string.ok, null);

        // The message
        builder.setMessage(message);

        // Create the alert dialog and display it
        AlertDialog theAlertDialog = builder.create();
        theAlertDialog.show();
    }

You can't show your Toast longer than the default time which is defined by Toast.LENGTH_LONG.

Since you want to show large message then you should use Dialog instead of Taost.

You can achieve that using Dialog as below...

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getApplicationContext());
dialogBuilder.setTitle("Mesage");
dialogBuilder.setText("Your message...");
dialogBuilder.setPositiveButton("OK",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

AlertDialog dialog = builder.create();
dialog.show();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top