【三】6.Android 中 Context 的理解及使用

來源:互聯網
上載者:User

標籤:android context activity

【一】Context的作用:訪問全域資訊


Context是訪問全域資訊的介面,比如說應用程式的資源(圖片資源、字串資源、其他資源...),

所以一些常用組件就會繼承Context,目的就是為了訪問資源,比如說Activity以及將要學習的Service。


建立項目來看下如何通過Context進行資源的訪問。

public class MainActivity extends Activity{    private TextView tv;        @Override    protected void onCreate(Bundle saveInstanceState){        super.onCreate(saveInstanceState);        tv = new TextView(this); // 這裡傳入參數必須有一個Context,因為這個TextView也需要訪問一些資源、全域資訊                                 // Activity也是Context的子類,所以可以傳入this        tv.setText("HelloAndroid"); //也可通過 R.id.hello_world 訪問string.xml中的字串資源        setContentView(tv);    }}


通過查看setText()方法的源碼:

setText(int resid){setText(getContext().getResources().getText(resid));}

首先通過getContext()擷取與它相關的Context對象,

也就是TextView所保留引用(傳入的那個參數)的Context對象,

也就是MainActivity的執行個體;

然後通過getResources()擷取當前程式的資源執行個體,

再通過getText(),給它一個id就可以返回資源的字串了。

這就是這個方法的內部實現。


也就是Android中,如果想訪問全域資訊,必須通過Context。

除了可以擷取字串,還能擷取其它資源,例片:

ImageView iv = new ImageView();iv.setImageResource(R.mimap.ic_launcher);setContentView(iv);


【二】Application的用途


很多情況下,我們需要在多個組件之間進行資料的共用,Android為我們提供了一種機制。

Context可以作為全域資訊共用的橋樑,所以我們可以用Context進行資訊的共用。

我們可以建立一個類,叫做App,繼承於Application。

public class App extends Application{}


然後開啟AndroidManifest.xml檔案,

添加斜體字中的資訊,<application android:name=".App" ……>,

通過這種方式,我們就自訂了Android的Application ,

而Application才是真正的全域內容物件。

在MainActivity中可以通過getApplicationContext()方法,

就可以獲得Application全域對象。













 


【三】6.Android 中 Context 的理解及使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.