Why Toast.makeText and not a new toast

It might be a noob question, but I was wondering why we should use the static method (makeText) to create a Toast, not a constructor.

Why should we use this:

makeText(Context context, CharSequence text, int duration)

instead of this:

new Toast(Context context, CharSequence text, int duration) 

This is the makeText method:

    public static Toast makeText(Context context, CharSequence text, int duration) {
        Toast result = new Toast(context);

        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);

        result.mNextView = v;
        result.mDuration = duration;

        return result;
    }

Why don't we do the following:

public Toast (Context context, CharSequence text, int duration) {
    this(context);

    LayoutInflater inflate = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
    TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
    tv.setText(text);

    this.mNextView = v;
    this.mDuration = duration;
}

I searched the website and source for some reason, but I did not find.

Please, if you have an idea, feel free to.

+5
source share
3 answers

The question basically comes down to when should I put the static method. The answer is simple - when your method has a very specific task and does not change the state of the object.

- , , add (int a, int b), a + b. a + b , -no ( ). - , , .

, ?

  • - , .

  • - ,

, , , ( , ). , .

, (makeText), , .

- Edit -

, , , , Toast.

Toast 2 Toast (. http://developer.android.com/reference/android/widget/Toast.html)

  • makeText ( , CharSequence, int duration), Toast, .

  • , Toast () , .

1, - Toast.makeText(, , ).show(); . .

2 : http://developer.android.com/guide/topics/ui/notifiers/toasts.html

Toast, setView (). , makeText (Context, int, int) .

@CFlex, , , , Toast.makeText(, , ), Toast, .

, - ClassName.getObject, , . , Singleton, , makeText ( N ), , Android.

+5

: : " , ?" , .

, , . , .

, Toast makeText, ( )

+2

As far as I know:

This is because we do not want to store a copy of the toast, which requires a constant amount of memory, until it is cleared by GarbageCollector.

And he always has access to the display, so your application does not require any set of permissions.

+1
source

All Articles