使用getApplicationcontext()和this在Toast.makeText()方法中有什么区别?

3

是否有特定情况下需要在Toast.makeText()方法的上下文参数中使用getApplicationcontext()或this?

 Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();

 Toast.makeText(getApplicationcontext(), "HI", Toast.LENGTH_LONG).show();

请参考以下网页了解有关编程的内容:https://dev59.com/EWkv5IYBdhLWcg3wxz2A 和 https://dev59.com/8XHYa4cB1Zd3GeqPJDsu - Shayan Pourvatan
2个回答

2

getApplicationContext:

根据开发者文档:getApplicationContext

返回当前进程的单个全局Application对象的上下文。通常仅在需要一个生命周期与当前上下文分离、与进程的生命周期而非当前组件相关联的上下文时才使用此方法。

用法:

您可以通过获取应用程序上下文来在整个应用程序中使用它。

public class YourApp extends Application
{
 static YourApp appstate;
 public void onCreate(Bundle savedInstanceState){
    super.onCreate();
    appstate = this;
   }
 public static YourApp getApplication(){
    return appstate;
   }
}

如何使用它:YourApp.getApplication();


this

在实例方法或构造函数中,this是指当前对象的引用。

用法:只要您能看到您的Activity Context,就可以使用它

例如:

public void onCreate(Bundled savedInstanceState)
{
 ...
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
}

如何区分在使用Toast.makeText()thisgetApplicationContext()的不同?

尝试在AynscTask中使用thisgetApplicationContext()来调用Toast.makeText()


你如何成为 Android 编程方面的专家?我很难理解程序本身,有什么提示可以让像您一样的编程新手变得更好吗? - sweet_revathy569

2
您可以关注以下内容:
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

“this”和getContext()是相同的。

[参考] [getContext(),getApplicationContext(),getBaseContext()和“this”的区别]1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接