Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎:Context 的作用與使用範例

編輯:關於 Android 程式設計

一、Context 是什麼

類別繼承關係

官方定義的含意

Context 是關於應用程式環境的全域資訊接口。它是一個抽象類別,具體實作由 Android 系統提供。透過它,你能存取應用專屬的資源與類別,也能向上呼叫應用層級的操作,例如啟動 Activity、發送廣播、接收 Intent 等。

換句話說,凡是「要跟系統或全域環境打交道」的事情,幾乎都得經過 Context。這也是為什麼 Activity、Service、Application 都直接繼承自它——它們本身就是一種 Context。

二、動手做個範例

範例專案 LearnContext 的 MainActivity.java:

package com.example.learncontext;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /* 範例① */
        /* TextView(Context context):建構子至少要傳入一個 Context,
           以便存取資源與全域資訊 */
        // TextView textView = new TextView(this);
        // textView.setText("Hello Android!");

        /* setText(int resid):傳入資源 ID
           Android 要存取全域資訊必須經過 Context */
        // textView.setText(R.string.hello_world);
        // setContentView(textView);
        // System.out.println(getResources().getText(R.string.hello_world));

        /* 範例②:取得圖示資源 */
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.ic_launcher);
        setContentView(imageView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

把註解區塊逐一放開執行,就能實際體會 Context 存取全域資訊的能力。

三、幾個常見疑問

為什麼 new TextView(this) 可以,new TextView(getApplicationContext()) 卻要小心?因為 Activity 這個 Context 帶有主題(Theme)資訊,會影響控制項的外觀;Application 的 Context 沒有主題,用在需要樣式的地方可能出現外觀異常。

什麼時候該用哪一個?一個實用的判斷準則是:跟 UI 有關的,一律傳 Activity;跟 UI 無關的長生命週期操作(例如自訂 Thread、單例中持有的物件),傳 getApplicationContext() 以避免持有 Activity 參照造成記憶體洩漏。

版權聲明:本文為博主原創文章,未經博主允許不得轉載。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved