Android 中的上下文到底是什么?为什么需要它?

发布于 2024-11-24 12:00:23 字数 153 浏览 3 评论 0原文

我也是 Android 开发和软件开发的新手。 我在 Android 代码中不断看到这个术语,称为“上下文”。 我知道它是 android.content 包中的一个类,但我不明白它到底是什么以及为什么在这么多地方需要它,特别是在构造函数中。

有人可以向我解释一下这个术语吗?

I am new to Android development and Software development too.
I keep seeing this term called - 'context' in Android code.
I know that it's a class in android.content package, but I don't understand what exactly is it and why is it needed in so many places, especially in the constructors.

Can someone please explain this term to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潜移默化 2024-12-01 12:00:23

顾名思义,它是应用程序/对象当前状态的上下文。它让新创建的对象了解发生了什么。通常,您调用它来获取有关程序的另一部分(活动、包/应用程序)的信息。

您可以通过调用 getApplicationContext()、getContext()、getBaseContext() 或 this(在活动类中时)来获取上下文。

上下文的典型用法:

Creating New objects: Creating new views, adapters, listeners:

TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),..);

Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(name, mode);

Accessing Components Implicitly: Regarding content providers, broadcasts, intent

getApplicationContext().getContentResolver().query(uri,...);

其副本来自此处

As the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

Typical use of context:

Creating New objects: Creating new views, adapters, listeners:

TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),..);

Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(name, mode);

Accessing Components Implicitly: Regarding content providers, broadcasts, intent

getApplicationContext().getContentResolver().query(uri,...);

Its copy from here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文