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

在 Eclipse 中掛載 Android Framework 源碼,告別 Ctrl 鍵無反應

編輯:關於 Android 程式設計

用 Eclipse 開發時,按住 Ctrl 點進 framework 類別卻只跳出「Source not found」,是每個人都遇過的尷尬。其實只要把源碼關聯好,這個問題幾分鐘就能解決。

操作步驟

先在專案上按右鍵,依序進入 Properties → Java Build Path → Libraries,找到 android.jar 並展開它。

展開後會看到一個 Source attachment 欄位,雙擊它就能指定源碼位置。這裡可以關聯 zip 檔或資料夾皆可。

源碼從哪裡來

最省事的方式是用 SDK Manager 下載對應 API Level 的「Sources for Android SDK」項目。下載完成後,源碼會落在 sdk/sources 目錄底下,裡面按平台版本分資料夾,挑一個跟你專案相符的選進去就可以了。

驗證成果

設定完畢後,隨便點開一個 framework 類別試試。以下就是 Button 的源碼:

@RemoteView
public class Button extends TextView {
    public Button(Context context) {
        this(context, null);
    }

    public Button(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.buttonStyle);
    }

    public Button(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(Button.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(Button.class.getName());
    }
}

看到這段程式碼,就代表關聯成功了。往後追 framework 的實作細節,不必再對著空白頁發呆。

順帶一提

從 Button 這個例子不難看出幾件事:它其實是 TextView 的子類別,這解釋了為什麼 Button 天生就支援文字與樣式設定;三個建構子層層退化,最終都指向系統內部的預設樣式;而它就只是把無障礙事件的類別名稱回報出去,沒有更多魔法。有源碼在手,這類「為什麼」都能自己找到答案。

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