2011-07-14 55 views
0

我也是Android開發和軟件開發的新手。 我一直在Android代碼中看到這個稱爲'上下文'的術語。 我知道它是android.content包中的一個類,但我不明白它到底是什麼,爲什麼它需要這麼多地方,特別是在構造函數中。Android中的上下文究竟是什麼?爲什麼它需要?

有人可以向我解釋這個詞。

+0

可能重複http://stackoverflow.com/questions/2870678/please-解釋-ME-上下文類中,機器人) – Mat

回答

1

顧名思義,它是應用程序/對象當前狀態的上下文。它可以讓新創建的對象瞭解到底發生了什麼。通常,您可以通過調用它來獲取有關程序另一部分(活動,程序包/應用程序)的信息

您可以通過調用getApplicationContext(),getContext(),getBaseContext()或this(在activity類中)。

典型的使用情境:

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,...); 

其從here副本

[在Android中,請給我解釋一下Context類](的