吐司:区别"本"和" getApplicationContext()"?
我的设备运行的是Android 5.1.1,我发现,如果我用
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();
我得到这个:
但是,如果我用 getApplicationContext()
而不是这个
,
But if I use getApplicationContext()
instead of this
,
Toast.makeText(getApplicationContext(), "This is a toast", Toast.LENGTH_SHORT).show();
我得到这个:
两者都直接从活动调用
这是为什么?
它与上下文都有与之相关联的主题做。使用这个
使用上下文(我假设你的活动
或片段
),有不同的主题不是应用程序上下文。
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.
如果您有需要使用的应用程序上下文有原因的,你可以在你的活动正在使用哪个主题包(一般是在设置你的的AndroidManifest.xml
)它应该显示圆敬酒。
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();