I just learned that I can use either:
Toast.makeText(MainActivity.this, R.string.some_string,Toast.LENGTH_SHORT).show();
or,
Toast.makeText(getApplicationContext(), R.string.some_string,Toast.LENGTH_SHORT).show();
To display a Toast in Android.
Earlier I thought context was actually a sort of handle to the parent window where it should be display but the documentation is unclear about this.
Then I came across this table:
It also doesn't seem to mention what context exactly to use for a Toast?
Is context like a "handle to parent window" for the sub-window like Toast? or does it actually allow the Toast.makeText
to get access to resources or something?
Why is it being used at all if the context doesn't matter?
For toasts, which are short-lived, you can usually use whatever context you want. Typically, you would use the activity context, but application context is fine as well.
A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.
The Toast. makeText() method is a pre-defined method which creates a Toast object. Parameters: This method accepts three parameters: context: The first parameter is a Context object which is obtained by calling getApplicationContext().
Here is an Android Toast example: Toast toast = Toast. makeText(getApplicationContext(), "This is a message displayed in a Toast", Toast. LENGTH_SHORT); toast.
Looking at Toast.java, I can see the Context
is used only for:
Resources
getText
which is actually same as #1So apparently there's no difference whether it's Activity
or ApplicationContext
, unless those resources depend on theme (which is not the case as far as I can tell).
And no, the context passed to Toast is not a handle to parent window in any sense.
I'd recommend to use the activity in your case. Since you're calling from the activity itself. The activity is a Context and you're using the method on the activity to get another context (the application). It is a little unnecessary.
However in the case you're calling a toast from somewhere else it might be a better idea to use the application, since the application will always be there while your app is active.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With