[英]What exactly is context in Android and why is it needed?
我也是 Android 開發和軟件開發的新手。 我一直在 Android 代碼中看到這個術語稱為“上下文”。 我知道它是 android.content package 中的 class,但我不明白它到底是什么以及為什么在這么多地方需要它,尤其是在構造函數中。
有人可以向我解釋這個術語嗎?
顧名思義,它是應用程序/對象的當前 state 的上下文。 它讓新創建的對象了解正在發生的事情。 通常,您調用它來獲取有關程序另一部分(活動、包/應用程序)的信息
您可以通過調用 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,...);
它的副本來自這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.