Toast: Difference between “this” and “getApplicationContext()”?

假如想象 提交于 2019-12-08 16:03:24

问题


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:

But if I use getApplicationContext() instead of this,

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

I got this:

Both are called directly from the activity.

Why is this?


回答1:


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();


来源:https://stackoverflow.com/questions/33045471/toast-difference-between-this-and-getapplicationcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!