Toast: Difference between "this" and "getApplicationContext()"?
Asked Answered
U

1

10

My device runs Android 5.1.1 and I found out that if I use

Toast.makeText(this, "This is a toast", Toast.LENGTH_SHORT).show();

I got this:

"round" toast

But if I use getApplicationContext() instead of this,

Toast.makeText(getApplicationContext(), "This is a toast", Toast.LENGTH_SHORT).show();

I got this:

rectangle toast

Both are called directly from the activity.

Why is this?

Umber answered 9/10, 2015 at 19:6 Comment(0)
O
13

It has to do with the Theme the Context has associated with it. Using this is using a context (I'm assuming your Activity or Fragment) that has a different theme than the Application Context.

If you have a reason you need to be using the application context, you can wrap it in whichever theme your activities are using (usually set in your AndroidManifest.xml) and it should show the "round" toast.

Toast.makeText(new ContextThemeWrapper(getApplicationContext(), R.style.AppTheme), "This is a toast", Toast.LENGTH_SHORT).show();
Ochlophobia answered 9/10, 2015 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.