简体   繁体   English

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

[英]What exactly is context in Android and why is it needed?

I am new to Android development and Software development too.我也是 Android 开发和软件开发的新手。 I keep seeing this term called - 'context' in Android code.我一直在 Android 代码中看到这个术语称为“上下文”。 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.我知道它是 android.content package 中的 class,但我不明白它到底是什么以及为什么在这么多地方需要它,尤其是在构造函数中。

Can someone please explain this term to me.有人可以向我解释这个术语吗?

As the name suggests, its the context of current state of the application/object.顾名思义,它是应用程序/对象的当前 state 的上下文。 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).您可以通过调用 getApplicationContext()、getContext()、getBaseContext() 或 this(在活动类中时)来获取上下文。

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它的副本来自这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM